使用EntityFramework Code First Approch进行实体关系映射

时间:2018-02-21 06:00:37

标签: entity-framework

我正在创建错误跟踪器应用程序并坚持映射。

用户实体:

public class User : Entity {
    public IList<Issue> Assignees { get; set; }
    public IList<Issue> Authors { get; set; }
}

问题实体:

public class Issue : SoftDeletableEntity {
    public User Author { get; set; }
    public long AuthorID { get; set; }

    public User Assignee { get; set; }
    public long AssigneeID { get; set; }
}

现在,当我添加迁移时,当前Code First模型的快照是:

CreateTable(
            "dbo.Issue",
            c => new {
                ID = c.Long(nullable: false, identity: true),
                AuthorID = c.Long(nullable: false),
                AssigneeID = c.Long(nullable: false),
                DeletedBy = c.String(),
                DeletedOn = c.DateTime(),
                IsDeleted = c.Boolean(nullable: false),
                Name = c.String(),
                CreatedOn = c.DateTime(nullable: false),
                ModifiedOn = c.DateTime(nullable: false),
                User_ID = c.Long(),
                User_ID1 = c.Long(),
            })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.User", t => t.AssigneeID, cascadeDelete: false)
            .ForeignKey("dbo.User", t => t.AuthorID, cascadeDelete: false)
            .ForeignKey("dbo.User", t => t.User_ID)
            .ForeignKey("dbo.User", t => t.User_ID1)
            .Index(t => t.AuthorID)
            .Index(t => t.AssigneeID)
            .Index(t => t.User_ID)
            .Index(t => t.User_ID1);

上面的迁移创建了AuthorIDAssigneeID,还添加了User_IDUser_ID1,因为我在“用户”表格中添加了以下属性。

public IList<Issue> Assignees { get; set; }
public IList<Issue> Authors { get; set; }

它创建了此User_IDUser_ID1,但我需要使用AuthorIDAssigneeID进行映射。

注意:我正在使用EntityFramework 6.0

如果我做错了什么,请告诉我如何能够实现上述目标,并告诉我。

提前致谢

1 个答案:

答案 0 :(得分:2)

将此添加到您应该解决问题的数据上下文中。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Issue>()
         .HasMany(x => x.Authors)
         .WithRequired(x => x.Author)
         .HasForeignKey(x => x.AuthorID);
    modelBuilder.Entity<Issue>()
         .HasMany(x => x.Assignees)
         .WithRequired(x => x.Assignee)
         HasForeignKey(x => x.AssigneeID);
}