search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

1 answers
Q&A Entity Framework数据迁移(Migrations)新增多对多关系,为什么如下代码不生成中间表?

0

数据库中有一张Blog表,还有一张Tag表,它们有各自属性。而一开始生成数据库而是直接通过EF生成的,也没有做过数据迁移。

现在希望把Blog和Tag进行多对多关系进行关联,由于线上数据库应用于生产环境,已经有了真实数据,所以只能使用EF数据迁移来完成了。

于是我在model层的Blog.cs里新增了如下代码:

public virtual IList Tags { get; set; }

然后在model层的Tag.cs里新增了如下代码:

public virtual ICollection Blogs { get; set; }

然后开始操作数据迁移,生成的数据迁移为代码如下:

    public override void Up()
    {
        //往dbo.blog表里新增了一列Tag_TagId
        AddColumn("dbo.Blogs", "Tag_TagId", c => c.String(maxLength: 128));
        //往dbo.Tags表里新增了一列Blog_BlogId1
        AddColumn("dbo.Tags", "Blog_BlogId1", c => c.String(maxLength: 128));
        
        CreateIndex("dbo.Blogs", "Tag_TagId");
        CreateIndex("dbo.Tags", "Blog_BlogId1");
        
        AddForeignKey("dbo.Blogs", "Tag_TagId", "dbo.Tags", "TagId");
        AddForeignKey("dbo.Tags", "Blog_BlogId1", "dbo.Blogs", "BlogId");
    }

由这段代码可见Blog和Tag表只是各自新增了外键进行1对1的关联,而不是我希望的多对多关系,还请各位大神指点。

对于这个问题解决方案我的猜想是:是不是对EF的多对多映射关系处理的不正确,需要加一些Attribute做下映射?。

万分感谢,祝好。


Your Answer
submit

1 answers
1

在别的地方找到了解决方案。

在DBContext的OnModelCreating写:

            modelBuilder.Entity()
                .HasMany(a => a.tags)
                .WithMany(t => t.Blogs)
                .Map(m =>
                {
                    m.ToTable("blog_tag"); //中间关系表表名
                    m.MapLeftKey("tagID"); //设置Activity表在中间表主键名
                    m.MapRightKey("blogID"); //设置Trip表在中间表主键名
                });

然后再生成迁移(或者自己在up里创blog_tag表和设置外键关系)。

2016-11-12 15:20:48

submit

Popular tool

vc9-vc14 (32+64 bit) runtime library collection (link below)

vc9-vc14 (32+64 bit) runtime library collection (link below)

Download the collection of runtime libraries required for phpStudy installation

VC9 32-bit

VC9 32-bit

VC9 32-bit phpstudy integrated installation environment runtime library

PHP programmer toolbox full version

PHP programmer toolbox full version

Programmer Toolbox v1.0 PHP Integrated Environment

VC11 32-bit

VC11 32-bit

VC11 32-bit phpstudy integrated installation environment runtime library

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use