Consider these model relations:
public class A
{
[Key]
public int Id { get; set; }
public int BId { get; set; }
public ICollection<B> Bs { get; set; }
}
public class D
{
[Key]
public int Id { get; set; }
public int BId { get; set; }
public ICollection<B> Bs { get; set; }
}
public class B
{
public int Id { get; set; }
public int CId { get; set; }
public C C { get; set; }
}
public class C
{
[Key]
public int Id { get; set; }
}
With this configuration:
modelBuilder.Entity<B>()
.HasKey(x => new { x.Id, x.CId });
modelBuilder.Entity<A>()
.HasMany(a => a.Bs)
.WithOne()
.HasForeignKey(b => b.Id)
.HasPrincipalKey(a => a.Id);
modelBuilder.Entity<D>()
.HasMany(a => a.Bs)
.WithOne()
.HasForeignKey(b => b.Id)
.HasPrincipalKey(a => a.Id);
The intent was to reuse B
's among A
and D
however EF Core creates foreign-key constraints on the table for B
meaning that I can't have entries that are associated with A
without being associated with B
also.
Is there a way to define the constraints so that it exists on A
and D
instead?