According to How to add a parent record with its children records in EF Core the following should work:
Model Builder
mb.Entity<IdentifierTable>().HasKey("StockID");
mb.Entity<StockTable>().HasKey("StockID");
mb.Entity<ProductTable>().HasKey("IdentifierID");
mb.Entity<GroupsTable>().HasKey("GroupId");
mb.Entity<StockTable>()
.HasOne(x => x.Identifier)
.WithOne(y => y.Stock)
.HasForeignKey<IdentifierTable>(y => y.StockID);
mb.Entity<StockTable>()
.HasOne(x => x.Group)
.WithMany(y => y.Stock)
.HasForeignKey(y => y.GroupId);
mb.Entity<ProductTable>()
.HasOne<IdentifierTable>(x => x.Identifier)
.WithOne(y => y.Product)
.HasForeignKey<IdentifierTable>(y => y.IdentifierID);
base.OnModelCreating(mb);
Relevant parts of StockTable
public int StockID { get; set; }
public int? GroupId { get; set; }
[...]
public IdentifierTable Identifier { get; set; }
public GroupsTable Group { get; set; }
Relevant parts of IdentifierTable
public int IdentifierID { get; set; }
public ProductTable Product { get; set; }
public int StockID { get; set; }
public StockTable Stock { get; set; }
Relevant parts of ProductTable
public int? IdentifierID { get; set; }
public IdentifierTable Identifier { get; set; }
[...]
Relevant parts of GroupsTable
public int GroupId { get; set; }
public List<StockTable> Stock { get; set; }
The actual program
foreach (var item in contexts.originalContext.StockTable
.Include(x=>x.Group)
.Include(x=>x.Identifier)
.ThenInclude(y=>y.Product))
{
contexts.destinationContext.StockTable.Add(item);
contexts.destinationContext.SaveChanges();
}
However, when saving the changes, I get an exception:
violation of FOREIGN KEY constraint "FK_EST_IDENT_PROD" on table "ProductTable" Foreign key reference target does not exist
I understood EF Core should add StockTable
's child properties as well (IdentifierTable
, ProductTable
, and distinct GroupsTable
). What am I doing wrong here?
The reason I'm using FluentAPI is because I'm working with a pre-made database, I can't edit table/column names, nor relationships. Could it be because IdentifierTable.StockID
is both primary key and foreign key?
I think I might have found a clue: Checking a tentative migration, I found EF Core is creating two foreign keys alright. However, it is creating both on IdentifierTable
. The relationships I aim for are:
- One
StockTable
has one and only oneIdentifierTable
. - One
IdentifierTable
has one or noneProductTable
. - One
StockTable
has one or noneGroupsTable
. - One
GroupsTable
has none, one, or multipleStockTable
.
I think I might not be able to use this database with EF Core. I tried scaffolding the models database-first, and EF Core didn't manage to understand a single foreign key relation.