Many-to-Many Repeat Record

I'm trying to build many, many relationships using an entity structure and a free 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; }
}
  • Any pizza must have several toppings.
  • Any file can be applied to several pizzas.

So in OnModelCreating()I call:

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

This gives me a good many-to-many relationship, but the problem is that I want the pizza to have multiple instances of the same topping , for example. double pepperoni

The database ToppingsForPizzathat is generated cannot support this ... I assume there must be a unique primary key.

Is there any way to do this?

EDIT: , , .

+2
3

. , .

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

Pizzas Toppings.....; -)

+2

, Topping. , :

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

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

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

(because it is likely that this is a unique composite key that prevents the addition of multiple fillers.)

0
source

All Articles