实体框架代码优先 - 来自同一个表的两个可空和一个非空外键

时间:2017-03-16 08:01:56

标签: entity-framework ef-code-first foreign-keys nullable ef-migrations

如何在这两个表和列之间为此问题设置正确的结构? 谢谢。

任务表:

public int EntryUserId{get;set;}
public virtual Users EntryUser{get;set;}

public int? AssignToUserId{get;set;}
public virtual Users AssignToUser{get;set;}

public int? CheckerUserId{get;set;}
public virtual Users CheckerUser{get;set;}

用户表:

public virtual IEnumerable<Tasks> EntryUser
public virtual ICollection<Tasks> AssignToUser
public virtual ICollection<Tasks> CheckerUser

在我的DbContext类中:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Tasks>()
                .HasRequired(m => m.EntrybyUser)
                .WithMany(t => t.EntryUser)
                .HasForeignKey(m => m.EntryUserId)
                .WillCascadeOnDelete(true);

    modelBuilder.Entity<Tasks>()
                .HasRequired(m => m.AssignToUser)
                .WithMany(t => t.AssignToUser)
                .HasForeignKey(m => m.AssignToUserId)
                .WillCascadeOnDelete(true);//for nullable

    modelBuilder.Entity<Tasks>()
                .HasRequired(m => m.CheckerUser)
                .WithMany(t => t.CheckerUser)
                .HasForeignKey(m => m.CheckerUserId)
                .WillCascadeOnDelete(true);//for nullable
    base.OnModelCreating(modelBuilder);

}

1 个答案:

答案 0 :(得分:1)

将其更改为:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Tasks>()
                    .HasRequired(m => m.EntryUser)
                    .WithMany(m=> m.EntryUser)
                    .HasForeignKey(m => m.EntryUserId)
                    .WillCascadeOnDelete(true);

        modelBuilder.Entity<Tasks>()
                    .HasOptional(m => m.AssignToUser)
                    .WithMany(t => t.AssignToUser)
                    .HasForeignKey(m => m.AssignToUserId)
                    .WillCascadeOnDelete(true);//for nullable

        modelBuilder.Entity<Tasks>()
                    .HasOptional(m => m.CheckerUser)
                    .WithMany(t => t.CheckerUser)
                    .HasForeignKey(m => m.CheckerUserId)
                    .WillCascadeOnDelete(true);//for nullable
        base.OnModelCreating(modelBuilder);

    }

和Users类:

public class Users
{
    public virtual ICollection<Tasks> EntryUser { get; set; }
    public virtual ICollection<Tasks> AssignToUser { get; set; }
    public virtual ICollection<Tasks> CheckerUser { get; set; }
}