Sto cercando di impostare una relazione molti a molti utilizzando EF Core e ASP.NET Core 2.1 e per ora non riesco a farlo funzionare e sembra che non capisco nemmeno la logica dietro.
Quindi ho impostato molte e molte relazioni usando ModelBuilder in questo modo:
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);
I miei modelli di entità:
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; }
}
E la mia tabella di join:
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; }
}
Ora, voglio impostare una relazione molte a molte tra le tabelle Ware e Component in modo che alla fine la mia tabella di join sia simile a questa.
Tables: WareId | ComponentId | ComponentWares |
1 | 1 | ComponentId | WareId |
2 | 2 | 1 | 1 |
| 1 | 1 |
| 2 | 1 |
| 2 | 1 |
Così tanti componenti potrebbero avere molti articoli (anche duplicati) e viceversa.
Ho provato ad aggiungere manualmente le voci utilizzando SQL Server Explorer ma sembra che non sia possibile aggiungere più ComponentId e WareId con gli stessi valori a causa del
HasKey(cw => new { cw.ComponentId, cw.WareId })
Ho letto che la riga sopra è necessaria per molte e molte relazioni in EF Core ma per mia comprensione nega l'idea di molte e molte relazioni ...
Devo rimuovere ComponentId cw.WareId key dal ModelBuilder e aggiungere Id nella tabella di join o è l'altra soluzione per questo?
Per il risultato atteso, dovresti definirlo con una relazione molti-a-molti.
Il tuo problema originale è causato dall'inserimento del valore duplex nella tabella centrale.
Dovresti inserire i record sotto a ComponentWares