Many-to-many relationship with duplicate entries

☆樱花仙子☆ 提交于 2019-12-02 00:35:07

You need to add a different primary key to your many to many relationship. That means it becomes an entity in it's own right

public class PizzaTopping
{   
    public int PizzaToppingId { get; set; }
    public int PizzaId { get; set; }
    public int ToppingId { get; set; }

    public virtual Pizza Pizza { get; set; }
    public virtual Topping Topping { get; set; }
}

public class Pizza
{ 
     public int PizzaId { get; set; } 
     public virtual ICollection<PizzaTopping> PizzaToppings { get; set; }
}

public class Topping
{   
     public int ToppingId { get; set; }
     public virtual ICollection<PizzaTopping> PizzaToppings { get; set; }
}

Doesn't make much sense applied to Pizzas and Toppings..... ;-)

I think you should consider double pepperoni as a separate Topping. But, you can also create a third class, like below:

public class PizzaTopping
{
    public int PizzaId { get; set; }
    public int ToppingId { get; set; }
    public int ToppingCount { get; set; }

    public virtual ICollection<Pizza> Pizzas { get; set; }
    public virtual ICollection<Topping> Toppings { get; set; }
}

public class Pizza
{
    public int PizzaId { get; set; }
}

public class Topping
{
    public int ToppingId { get; set; }
}

Another possible solution is to turn off code first and model verification, create a new primary key as described by others, create foreign keys in your relationship table for PizzaId and ToppingId, then modify your mapping to include the foreign keys.

modelBuilder.Entity<Pizza>()
            .HasMany(p => p.Toppings)
            .WithMany()
            .Map(m => m.ToTable("ToppingsForPizza")
               .MapLeftKey("PizzaId")
               .MapRightKey("ToppingId"));

(Because it's likely that it's a unique composite key that's preventing the addition of multiple toppings.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!