首页 > 解决方案 > EF6 代码首先是多对多,具有与其中一个实体上的集合相同类型的附加属性

问题描述

我知道这个问题在 SO 上有很多类似的问题,但我找不到与我的完全一样的问题,但我可能是错的,并且存在一个。所以这是我的问题:
我们有两个实体(C# poco 类),MeetingUser,每个实体都包含另一个实体的集合。代码,为简洁起见缩短:

public class Meeting
{
    public int ModeratorId { get; set; }
    public virtual User Moderator { get; set; }    // Property of type User

    public virtual ICollection<User> Participants { get; set; } // Collection of User
}

这是第二个:

public class User
{
    public virtual ICollection<Meeting> Meetings { get; set; }
}  

现在,在添加迁移时,人们会期望 EF 会创建一个链接表,类似于MeetingUsers ,如果我省略了Moderator属性,它实际上会创建它。但是,当我添加Moderator属性(与Participants中的项目类型相同)时,EF 会删除链接表并在迁移中添加一个Meeting_Id列。以下是迁移:
第一次迁移,只有两个类的集合,没有Meeting上的额外Moderator属性:

public override void Up()
    {   
        CreateTable(
            "dbo.MeetingUsers",
            c => new
                {
                    Meeting_Id = c.String(nullable: false, maxLength: 128),
                    User_ID = c.Int(nullable: false),
                })
            .PrimaryKey(t => new { t.Meeting_Id, t.User_ID })
            .ForeignKey("dbo.Meetings", t => t.Meeting_Id, cascadeDelete: true)
            .ForeignKey("dbo.Users", t => t.User_ID, cascadeDelete: true)
            .Index(t => t.Meeting_Id)
            .Index(t => t.User_ID);
        
    }  

您可以看到 EF 很好地创建了链接表(为简洁起见,我省略了会议用户)。
这是我添加Moderator属性后 EF 添加的第二个迁移:

public override void Up()
    {
        DropForeignKey("dbo.MeetingUsers", "Meeting_Id", "dbo.Meetings");
        DropForeignKey("dbo.MeetingUsers", "User_ID", "dbo.Users");
        DropIndex("dbo.MeetingUsers", new[] { "Meeting_Id" });
        DropIndex("dbo.MeetingUsers", new[] { "User_ID" });
        AddColumn("dbo.Users", "Meeting_Id", c => c.String(maxLength: 128));
        AddColumn("dbo.Meetings", "ModeratorId", c => c.Int());
        AddColumn("dbo.Meetings", "User_ID", c => c.Int());
        CreateIndex("dbo.Users", "Meeting_Id");
        CreateIndex("dbo.Meetings", "ModeratorId");
        CreateIndex("dbo.Meetings", "User_ID");
        AddForeignKey("dbo.Meetings", "ModeratorId", "dbo.Users", "ID");
        AddForeignKey("dbo.Users", "Meeting_Id", "dbo.Meetings", "Id");
        AddForeignKey("dbo.Meetings", "User_ID", "dbo.Users", "ID");
        DropTable("dbo.MeetingUsers");
    }  

如您所见,EF 删除了链接表并在用户表上添加了一列,这不是我想要的。相反,我想保留链接表,只需将新列ModeratorId添加到会议表中。
我该如何做到这一点?我可能会补充一点,我们始终使用数据注释,而不是 EF 的 fluent api。

谢谢,
阿什隆

标签: c#entity-framework-6ef-code-firstentity-framework-migrations.net-4.6.1

解决方案


您可以手动定义链接表,一切顺利。

 public class Meeting
 {
    public int ModeratorId { get; set; }
    public virtual User Moderator { get; set; }    // Property of type User


}

And here's the second one:  

public class User
{
    .....
} 
public MeetingUser{

   public int UserId{get;set;}
   public virtual User User{get;set;}
   public int MeetingId {get;set;}
   public virtual Meeting Meeting {get;set;}
}

推荐阅读