I'm in .net8 ef core with postgres database and code first approach.
I have these two class:
public class Soggetto
{
public long Id { get; set; }
public virtual Azienda Azienda { get; set; }
public long AziendaId { get; set; }
}
public class Azienda
{
public long Id { get; set; }
public virtual Soggetto Soggetto { get; set; }
public long SoggettoId { get; set; }
}
and these two fluent configuration:
public class SoggettoConfiguration : BaseAziendaAnagraficaEntityConfiguration<Soggetto>
{
public override void Configure(EntityTypeBuilder<Soggetto> builder)
{
base.Configure(builder);
builder
.HasOne(soggetto => soggetto.Azienda)
.WithOne(azienda => azienda.Soggetto)
.HasForeignKey<Soggetto>(x => x.AziendaId);
}
}
public class AziendaConfiguration : BaseEntityConfiguration<Azienda>
{
public override void Configure(EntityTypeBuilder<Azienda> builder)
{
base.Configure(builder);
builder
.HasOne(azienda => azienda.Soggetto)
.WithOne(soggetto => soggetto.Azienda)
.HasForeignKey<Azienda>(azienda => azienda.SoggettoId);
}
}
So when EF generate code for migration, I find foreign key to Soggetto in Azienda table and no foreign key to Azienda in Soggetto table. My expectation is to find both FK: SoggettoId in Azienda table and AziendaId in Soggetto table.
Any idea?
EDIT:
Clarification
Azienda is like a Tenant, every table has a TenantId to identify who is the owner of the record. Soggetto is like Subject, it could be person, delivery guy, client, supplier and a tenant... i mean something with Name, email, and other information.
So, every Soggetto (e.g.subject,person) has one Azienda (tenant) to identify the owner (eg. those are my clients). On the other way Azienda (tenant) has a name, email and other information stored in Soggetto.
I guess that you have a small misunderstanding about one-to-one relationships (or I have misunderstood your question). Basically it is covered in the EF Core docs - One-to-one relationships:
If you want to simulate the "truly" one-to-one relationship the only option via EF is to use owned entity types as mentioned in the linked previously "Required navigations" portion of the docs:
If you have several one-to-one relationships between tables (i.e.
Soggettocan have a dependedAziendaandAziendacan have another dependedSoggetto) then you will need to have several properties. For example something along these lines (not tested):And map them correspondingly with the Fluent API. For example: