I am working with EF Core 5.0 in an ASP.NET Core Web API.
I have an entity called Child
public class Child
{
public Guid Id { get; set; }
public Guid FirstParentId { get; set; }
public Guid SecondParentId { get; set; }
// Some other properties
}
The above child is a property in two parent tables called FirstParent and SecondParent:
public class FirstParent
{
public Guid Id { get; set; }
public Child Child { get; set; }
// Some other properties
}
public class SecondParent
{
public Guid Id { get; set; }
public Child Child { get; set; }
// Some other properties
}
While configuring the foreign key relationship, I followed FluentAPI as follows in
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<FirstParent>().HasOne(a => a.Child).WithOne().HasForeignKey<Child>(b => b.FirstParentId);
modelBuilder.Entity<SecondParent>().HasOne(a => a.Child).WithOne().HasForeignKey<Child>(b => b.SecondParentId);
}
While creating the tables, it created as excepted. But while inserting some data into the FirstParent, I get an exception:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Child_SecondParent_SecondParentId". The conflict occurred in database "Tester", table "dbo.SecondParent", column 'Id'.
I cannot create all the child tables for every parent as I have lot of dependencies.
Am I missing anything more to configure? Any solutions?
Thanks in advance