Reputation: 509
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?
Upvotes: 1
Views: 944
Reputation: 26382
This is a database modeling question (not EF core) and we would need more real life information to really help.
Be that as it may, the foreign key is properly placed from your code on A
and D
. So the question is: which table is the child table? Check here for a more extensive answer: Where should I store a foreign key?
Placing the FK on the wrong side, you endanger the integrity of your data.
The only other relationship you can create, are both keys on the B table, which means that in order to create a B
value you need both A
and D
.
Upvotes: 1