I am trying to setup a specific relationship using FluentAPI on 2 entities. See details below
public abstract class Entity
{
[Key]
public int Id { get; set; }
}
public class Inventory: Entity
{
public int Version { get; set; }
public string Set_num { get; set; }
[JsonIgnore]
public virtual ICollection<InventoryPart> InventoryParts { get; set; }
}
public class InventoryPart : Entity
{
public int Inventory_id { get; set; }
public string Part_num { get; set; }
public int Color_id { get; set; }
public int Quantity { get; set; }
public string Is_spare { get; set; }
public string Img_url { get; set; }
[JsonIgnore]
public virtual UserPart? UserPart { get; set; }
}
public class UserPart : Entity
{
public string Part_num { get; set; }
public int Color_id { get; set; }
public int Quantity { get; set; }
public string Location { get; set; }
[JsonIgnore]
public virtual ICollection<InventoryPart> InventoryParts { get; set; }
}
OnModelCreating code:
modelBuilder.Entity<Inventory>()
.HasMany(b => b.InventoryParts)
.WithOne()
.HasForeignKey(lim => lim.Inventory_id);
modelBuilder.Entity<InventoryPart>()
.HasKey(l => new { l.Part_num, l.Color_id }); // This IS NOT unique! Inventory_id, Part_num, Color_id, Is_spare would be the unique compound key
modelBuilder.Entity<UserPart>()
.HasKey(u => new { u.Part_num, u.Color_id }); // This IS unique
modelBuilder.Entity<UserPart>()
.HasMany(u => u.InventoryParts)
.WithOne(l => l.UserPart)
.HasForeignKey(l => new { l.Part_num, l.Color_id });
The goal is to filter an InventoryPart and include InventoryParts and the linked UserPart.
public class GetSetPartsBySpecification : Specification<Inventory>, ISingleResultSpecification
{
public GetSetPartsBySpecification(string setnum)
{
Query
.Where(inv => inv.Set_num == setnum)
.Include(ip => ip.InventoryParts)
.ThenInclude(ip=>ip.UseParts)
.AsSplitQuery();
}
}
Notes on the data: Inventory and InventoryParts are imported into a SQLite database periodically. Inventory.Id is the InventoryPart.Inventory_id and is NOT autogenerated, it gets the value from the Excel import file.
An InventoryPart has a many-to-one-or-zero relationship with UserPart.
A UserPart has a one-to-many relationship with InventoryPart.
I don't need the reverse relationship, UserParts.InventoryParts
Question
Is it possible to define a relationship using Fluent API on the above entities structure? You can see my attempt above. I get an error because .HasKey(l => new { l.Part_num, l.Color_id }) on the InventoryPart is not unique.
Notes
I have a version of this working using a set of tables that I create during the import process but I would prefer to us the existing data structure. I can add that code if requested.