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外鍵列。
但是,由於與用戶的另一種關係,似乎不可能。 有沒有解決方法?
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
欲瞭解更多信息,我還添加流暢的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
@Ray編輯我的回答你會的。必須添加'WillCascadeOnDelete(false)'到一個可能的關係 – Eranga 2012-02-20 10:39:52