[英]how to define many-to-many and one-to-many relations between two entities in code first?
我先使用實體框架代碼創建一個網站,其中:用戶可以出售許多產品:一對多。 用戶可以購買許多產品,而產品可以被許多用戶購買:多對多。 我不斷收到錯誤:
System.Data.SqlClient.SqlException:'在表'UserProducts'上引入FOREIGN KEY約束'FK_dbo.UserProducts_dbo.Products_Product_ProductId'可能會導致循環或多個級聯路徑。 指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束。
我確實希望進行級聯刪除,以便刪除屬於已刪除帳戶的用戶的產品,或從UserProduct表中刪除屬於已刪除用戶或已刪除產品的記錄。 我究竟做錯了什么?
這是User類:
public class User
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public ICollection<Product> Products { get; set; }
[InverseProperty("Users")]
public ICollection<Product> Cart { get; set; }
public User()
{
Products = new List<Product>();
Cart = new List<Product>();
}
}
這是產品類:
public class Product
{
[Key]
public int ProductId { get; set; }
public int OwnerId { get; set; }
public string Title { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
public byte[] Picture1 { get; set; }
public byte[] Picture2 { get; set; }
public byte[] Picture3 { get; set; }
[ForeignKey("OwnerId")]
public User User { get; set; }
public ICollection<User> Users { get; set; }
public Product()
{
Users = new List<User>();
}
}
首先,我需要為用戶與產品之間的多對多關系中的中間表編寫一個類:
public class UserProduct
{
[Key, Column(Order = 0), ForeignKey("User")]
public int UserId { get; set; }
[Key, Column(Order = 1), ForeignKey("Product")]
public int ProductId { get; set; }
public User User { get; set; }
public Product Product { get; set; }
}
這使我可以禁用從此表刪除到用戶表的級聯(覆蓋上下文類中的OnModelCreating):
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserProduct>().HasRequired(t =>
t.User).WithMany(t => t.Cart).WillCascadeOnDelete(false);
}
禁用級聯工作是因為:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.