I have two entities, Prospect
and Person
, what I'm trying to do is use Prospect.ID
as the primary key on Prospect
table and as the foreign key of PersonID
, my idea 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 though I don't 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)
PersonDto
:
public class PersonDto : DtoBase
{
public PersonDto()
{
}
public ProspectDto Prospect { get; set; }
}
ProspectDto
:
public class ProspectDto : DtoBase
{
public ProspectDto()
{
}
public PersonDto Person { get; set; } = new PersonDto();
}
DtoBase
:
public abstract class DtoBase
{
public Guid ID { get; protected set; }
}
Thanks.
Using attributes only, without FluentAPI:
I don't know what is equivalent of
ForeignKey
in FluentAPI. All other (Key and InverseProperty) are configurable, but why use two methods instead one.Code above generates following migration code:
Looks very close to what you need.