Skip to content

Commit

Permalink
Change Many-to-many relationship configuration in Fluent API to ease …
Browse files Browse the repository at this point in the history
…Specifications.

Because the support for scaffolding many-to-many relationships from the database is not yet added (dotnet/efcore#22475).
  • Loading branch information
s-e-r-O committed Mar 21, 2021
1 parent b234119 commit 5afb28a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 16 deletions.
2 changes: 2 additions & 0 deletions API/src/TheGreatPizzaTest.Core/Entities/Ingredient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ public partial class Ingredient : Entity
public Ingredient()
{
PizzaToppings = new HashSet<PizzaTopping>();
Pizzas = new HashSet<Pizza>();
}
public string Name { get; set; }

public virtual ICollection<PizzaTopping> PizzaToppings { get; set; }
public virtual ICollection<Pizza> Pizzas { get; set; }
}
}
2 changes: 2 additions & 0 deletions API/src/TheGreatPizzaTest.Core/Entities/Pizza.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ public partial class Pizza : Entity
public Pizza()
{
PizzaToppings = new HashSet<PizzaTopping>();
Ingredients = new HashSet<Ingredient>();
}

public string Name { get; set; }

public virtual ICollection<PizzaTopping> PizzaToppings { get; set; }
public virtual ICollection<Ingredient> Ingredients { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,24 +38,27 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
});

modelBuilder.Entity<PizzaTopping>(entity =>
{
entity.HasKey(e => new { e.PizzaId, e.IngredientId })
.HasName("PK_PizzaTopping");

entity.HasIndex(e => e.IngredientId, "IX_PizzaToppings_IngredientId");

entity.HasIndex(e => e.PizzaId, "IX_PizzaToppings_PizzaId");
entity.HasMany(e => e.Ingredients)
.WithMany(e => e.Pizzas)
.UsingEntity<PizzaTopping>(
j => j
.HasOne(pt => pt.Ingredient)
.WithMany(p => p.PizzaToppings)
.HasForeignKey(pt => pt.IngredientId),
j => j
.HasOne(pt => pt.Pizza)
.WithMany(p => p.PizzaToppings)
.HasForeignKey(pt => pt.PizzaId),
j =>
{
j.HasKey(pt => new { pt.PizzaId, pt.IngredientId })
.HasName("PK_PizzaTopping");

entity.HasOne(d => d.Ingredient)
.WithMany(p => p.PizzaToppings)
.HasForeignKey(d => d.IngredientId);
j.HasIndex(pt => pt.IngredientId, "IX_PizzaToppings_IngredientId");

entity.HasOne(d => d.Pizza)
.WithMany(p => p.PizzaToppings)
.HasForeignKey(d => d.PizzaId);
j.HasIndex(pt => pt.PizzaId, "IX_PizzaToppings_PizzaId");
}
);
});

OnModelCreatingPartial(modelBuilder);
Expand Down

0 comments on commit 5afb28a

Please sign in to comment.