【问题标题】:DeleteRule for Many-to-many relationships ef codefirst多对多关系的 DeleteRule ef codefirst
【发布时间】:2014-04-24 23:09:19
【问题描述】:

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

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

问题:我无法删除 cartsproducts

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

请帮我用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)
{
  // ??
}

【问题讨论】:

    标签: c# asp.net entity-framework many-to-many code-first


    【解决方案1】:

    这应该适合你

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2013-07-16
      • 1970-01-01
      • 2018-06-02
      相关资源
      最近更新 更多