DeleteRule for Many-to-many relationships ef codefirst

本文关键字:ef codefirst relationships Many-to-many for DeleteRule | 更新日期: 2023-09-27 18:00:15

我正在建设一个电子商务网站。我想存储创建的每个购物车的数据。因此,我在推车产品之间建立了多对多的关系。

  • 如果产品与购物车相关,则会出现错误
  • 如果购物车与产品相关,它也会给出错误

问题:我无法删除购物车产品

我希望能够在不删除产品的情况下删除购物车。

请帮我用FluentAPI编写规则。

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
    public double Price { get; set; }
    public int StockCount  { get; set; }
    [Required]
    public Category Category { get; set; }
    [Required]
    public Brand Brand { get; set; }
    public ICollection<Media> Media { get; set; }
    public ICollection<Comment> Comments { get; set; }
    public ICollection<Cart> Carts { get; set; }
}
public class Cart
{
    [Key]
    public int CartId { get; set; }
    public bool Active { get; set; }
    public ICollection<Product> Products { get; set; }
    [Required]
    public UserObject User { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  // ??
}

DeleteRule for Many-to-many relationships ef codefirst

这应该适用于

public class Cart
{
    [Key]
    public int CartId { get; set; }
    public ICollection<Product> Products { get; set; }
}
public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

这是正确的映射配置:

modelBuilder.Entity<Cart>()
    .HasMany(c => c.Products)
    .WithMany()
    .Map(m =>
    {
        m.MapLeftKey("CartId");
        m.MapRightKey("ProductID");
        m.ToTable("CartProducts");
    });

还有一个有用的资源:http://msdn.microsoft.com/en-us/data/hh134698.aspx