Using ID as Primary key and foreign key at same time.
See original GitHub issueI have two entites, Prospect and person, what I’m trying to do is use Prospect.ID as primary key on ProspectTable and as foreignkey of PersonID, my ideia is use the same ID for both entities without the need of a PersonID on my Prospect entity. When the prospect is being saved on database, it tries to save a PersonID even I not have this property on my Prospect entity, I would like to know if ef core supports this kind of relationship.
Here’s what I got on my model builder.
modelBuilder.Entity<ProspectDto>(builder => { builder.ToTable("Prospects"); builder.HasKey(prospect => prospect.ID); });
modelBuilder.Entity<PersonDto>(builder => { builder.HasOne(p => p.Prospect).WithOne().HasForeignKey<ProspectDto>(pe => pe.ID); });
Here’s what is being executed on database:
INSERT INTO [Prospects] ([ID], [PersonID]) VALUES (@p421, @p422),
Thanks.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:1
- Comments:9 (4 by maintainers)
@breyed - It is ambiguous not just because of being one-to-one but also the property specified in FK attribute being present on both side. Whenever combination of
ForeignKeyAttribute
&InverseProperty
causes ambiguous/incorrect model configuration, we throw exception because we don’t know what to make out from those attribute. It cannot be overridden by fluent API, the attribute combination needs to be corrected to be consistent.Therefore removing annotations removes the exception. If you specifying relationship using fluent API only and facing issues then please file a new issue with relevant details
I’m pretty sure now that the issues with EF trying to use nonexistent columns were due to
HasForeignKey
andHasPrincipalKey
not being specified. Thanks for the help. Based on my experience, I added #7561 as a feature request to help with troubleshooting these kinds of problems.