I'm trying to setup a many to many relationship using EF Core and ASP.NET Core 2.1 and as for now I cannot get this working and it seems I do not understand the logic behind it either.
So I have setup many to many relationship using ModelBuilder like this:
builder.Entity<ComponentWare>().HasKey(cw => new { cw.ComponentId, cw.WareId });
builder.Entity<ComponentWare>()
.HasOne(x => x.Component)
.WithMany(x => x.ComponentWares)
.HasForeignKey(x => x.ComponentId);
builder.Entity<ComponentWare>()
.HasOne(x => x.Ware)
.WithMany(x => x.ComponentWares)
.HasForeignKey(x => x.WareId);
base.OnModelCreating(builder);
My entity models:
public class Component
{
public int ComponentId { get; set; }
public string Number { get; set; }
public string Name { get; set; }
public string MaterialType { get; set; }
public decimal? Cost { get; set; }
public float? Weight { get; set; }
public sbyte ComponentType { get; set; }
public sbyte SourceType { get; set; }
public string Comment { get; set; }
public string Author { get; set; }
public string AddedBy { get; set; }
public DateTime? ModifiedDate { get; set; }
public virtual ICollection<BookComponent> BookComponents { get; set; }
public virtual ICollection<ComponentWare> ComponentWares { get; set; }
}
public class Ware
{
public int WareId { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public decimal? Quantity { get; set; }
public string Unit { get; set; }
public decimal? Converter { get; set; }
public DateTime? Date { get; set; }
public virtual ICollection<ComponentWare> ComponentWares { get; set; }
}
And my join table:
public class ComponentWare
{
public int ComponentId { get; set; }
public Component Component { get; set; }
public int WareId { get; set; }
public Ware Ware { get; set; }
public int Quantity { get; set; }
public float Length { get; set; }
public string Unit { get; set; }
}
Now, I want to setup a many to many relationship between Ware and Component tables so that in the end my join table would look like this.
Tables: WareId | ComponentId | ComponentWares |
1 | 1 | ComponentId | WareId |
2 | 2 | 1 | 1 |
| 1 | 1 |
| 2 | 1 |
| 2 | 1 |
So many components could have many wares ( also duplicated ) and vice versa.
I have tried to manually add entries using SQL Server Explorer but it seems I cannot add multiple ComponentId and WareId with the same values because of the
HasKey(cw => new { cw.ComponentId, cw.WareId })
I've read that the line above is necessary for many to many relationship in EF Core but for my understanding it denies the idea of many to many relationship...
Should I remove ComponentId cw.WareId key from the ModelBuilder and add Id in the join table or is the another solution for this ?
For your expected result, you should define it with many-to-many relationship.
Your original issue is caused by inserting duplex value in the middle table.
You should insert the records below to ComponentWares