0

如何在這兩個表和列之間爲此問題設置正確的結構? 謝謝。實體框架代碼優先 - 來自同一個表的兩個可爲空和一個非空外鍵

任務表:

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); 

} 

回答

0

將其更改爲:

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); 

    } 

和用戶類:

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