Question

I'm building an e-commerce website. I want to store data of every shopping cart created. Thus, I made a many-to-many relationship between carts and products.

  • If a product is related to a cart it gives an error
  • If a cart is related to a product it also gives an error.

Problem: I cannot delete carts or products.

I want to be able to delete carts without deleting products.

Please help me to write the rule with 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)
{
  // ??
}
Was it helpful?

Solution

This should work for you

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; }
}

... here's the correct mapping configuration:

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

And a helpful resource: http://msdn.microsoft.com/en-us/data/hh134698.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top