1

我有以下兩個實體如何設置NOT NULL外鍵的屬性多重關係

public class User 
{ 
     [Key] 
     public int Id { get; set; } // PK 

     // for many-to-many relation with Booking.Members 
     public virtual ICollection<Booking> Bookings { get; set; } 
} 

public class Booking 
{ 
     public Booking() 
     { 
      Members = new List<User>(); 
     } 

     public int Id { get; set; } // PK 

     [ForeignKey("UserByCreated")] 
     public int UserByCreatedId { get; set; } // FK 
     public virtual User UserByCreated { get; set; } 

     // for many-to-many relation with User.Bookings 
     public virtual ICollection<User> Members { get; set; } 

} 

如上圖所示,用戶和預訂有兩種不同的關係,一個是多到多,另一個是外鍵關係。

我想要做的是在Bookings表中有一個具有NOT NULL條件的UserByCreatedId外鍵列。

但是,由於與用戶的另一種關係,似乎不可能。 有沒有解決方法?

回答

2

使用Fluent API配置關係,因爲EF在兩個實體之間存在多個關係時無法識別關係。

編輯

UserByCreated關係需要改變到可選的,以避免多路徑刪除問題。

public class Booking 
{ 
     public Booking() 
     { 
      Members = new List<User>(); 
     } 

     public int Id { get; set; } // PK 

     [ForeignKey("UserByCreated")] 
     public int? UserByCreatedId { get; set; } // FK 

     public virtual User UserByCreated { get; set; } 

     public virtual ICollection<User> Members { get; set; }  
} 

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<User>().HasMany(u => u.Bookings) 
     .WithMany(b => b.Members); 
    modelBuilder.Entity<Booking>().HasOptional(u => u.UserByCreated) 
     .WithMany() 
     .HasForeignKey(b => b.UserByCreatedId) 
     .WillCascadeOnDelete(false); 
} 
+0

UserByCreated和UserByCreatedId性能在預定實體不用戶實體,所以「modelBuilder.Entity ().HasRequired(B => b.UserByCreated).WithMany()。HasForeignKey(B => b.UserByCreatedId) ;「可能是正確的。順便說一句,即使我做了你的建議,我得到了以下異常:「在表'BookingUsers'上引入FOREIGN KEY約束'FK_BookingUsers_Users_UserId'可能導致循環或多個級聯路徑。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束。\ r \ n不能創建約束。請參閱以前的錯誤。「 – Ray 2012-02-20 10:22:11

+0

欲瞭解更多信息,我還添加流暢的api爲多對多關係如下「modelBuilder.Entity () .HasMany(b => b.Members) .WithMany(u => u.Bookings) 。地圖(M => { m.ToTable( 「BookingUsers」); m.MapLeftKey( 「BookingId」); m.MapRightKey( 「用戶ID」); }); – Ray 2012-02-20 10:24:53

+0

@Ray編輯我的回答你會的。必須添加'WillCascadeOnDelete(false)'到一個可能的關係 – Eranga 2012-02-20 10:39:52