-
Notifications
You must be signed in to change notification settings - Fork 3.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Referencing Base Type and Sub Type in same entity results in Ambiguous FK exception #26961
Comments
@jamesfera This is allowed, but using the same FK property for multiple relationships requires explicit configuration. For example: modelBuilder.Entity<Zoo>(b =>
{
b.HasMany(e => e.Animals).WithOne(e => e.Zoo).HasForeignKey(e => e.ZooId);
b.HasMany(e => e.Tigers).WithOne(e => e.Zoo).HasForeignKey(e => e.ZooId);
}); |
Thanks @ajcvickers. I tried configuring each one separately but not both at the same time. The error message led me astray...
|
Unfortunately, the suggested workaround does not work. After adding: modelBuilder.Entity<Zoo>(b =>
{
b.HasMany(e => e.Animals).WithOne(e => e.Zoo).HasForeignKey(e => e.ZooId);
b.HasMany(e => e.Tigers).WithOne(e => e.Zoo).HasForeignKey(e => e.ZooId);
}); to
Tested on latest EF Core 7.0.13 (and also on above mentioned 6.0.0) |
I found one working workaround (which doesn't use explicit FK configuration) but it looks more like a limited hack: public class Zoo
{
public int Id { get; set; }
public IEnumerable<Animal> Animals { get; set; }
// public IEnumerable<Tiger> Tigers { get; set; } <= THIS DOESN'T WORK!
[NotMapped] public IEnumerable<Tiger> Tigers => Animals.OfType<Tiger>();
} The loading of var zoo = context.Zoos.Include(x => x.Animals.Where(y => y is Tiger)).First(); and the loading of nested properties like So I still think that navigation for sub-types ( @ajcvickers please reopen this issue. |
@roji Hi MS team, should I create a new issue or you can reopen this one? |
When referencing hierarchical relationships, EF Core does not take into account the fact that a sub-type has the same FK as its base-type.
Given that Tiger is guaranteed to have the same
ZooId
as Animal, it seems like this case should be allowed (unless I'm missing something).Given this model:
This works:
This works:
This does NOT work:
Test:
EF Core version: 6.0.0
The text was updated successfully, but these errors were encountered: