多到多用重复的条目关系 [英] Many-to-many relationship with duplicate entries
问题描述
我试图建立一个多使用实体框架和流畅的API一对多的关系,但我坚持努力让重复的条目。以下是我有:
I'm trying to build a many to many relationship using the entity framework and fluent API, but I'm stuck trying to allow duplicate entries. Here is what I have:
public class Pizza
{
public int PizzaId { get; set; }
public virtual ICollection<Topping> Toppings { get; set; }
}
public class Topping
{
public int ToppingId { get; set; }
}
- 任何比萨饼应该可以有多个浇头。
- 任何摘心可应用于多个比萨饼。
因此,在 OnModelCreating()
我称之为:
So in OnModelCreating()
I call:
modelBuilder.Entity<Pizza>()
.HasMany(p => p.Toppings)
.WithMany()
.Map(m => m.ToTable("ToppingsForPizza"));
这给我一个很好的许多一对多的关系,但问题是我希望有一个比萨饼能够具有相同的馅料 STRONG>例如多个实例双辣
That give me a nice many-to-many relationship, but the problem is I want a pizza to be able to have multiple instances of the same topping e.g. double pepperoni
这将产生无法支持 ToppingsForPizza
数据库......我猜,因为需要有一个唯一的主键。
The ToppingsForPizza
database that is generated cannot support that... i'm guessing because there needs to be a unique primary key.
有没有办法做到这一点?
Is there a way to do this?
编辑:我的实际问题无关比萨饼,这仅仅是我想出了一个例子
My actual problem has nothing to do with pizza, this is just the example I came up with.
推荐答案
您需要将不同的主键,您的许多添加到一对多的关系。这意味着它成为一个实体在它自己的权利。
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..... ;-)
这篇关于多到多用重复的条目关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!