I moved my entities with a 1:0..1
relationship from EF6 to EF Core 7 and I want to define their relationships.
Here are my entities (simplified for the question):
public class MyEntity
{
public Guid Id { get; set; }
public virtual MyGroup MyEntityMyGroup{ get; set; }
}
public class MyGroup
{
public Guid Id { get; set; }
public virtual MyEntity MyEntity{ get; set; }
}
My EF6 DbContext class has the following configuration inside OnModelCreating
:
modelBuilder.Entity<MyEntity>()
.HasRequired(myEntity => myEntity.MyEntityMyGroup)
.WithOptional(group => group.MyEntity);
What is the equivalent of the configuration above in EF Core 7?
(I do not have a nullable foreign key on the MyGroup
entity.)
In EF6, the following
modelBuilder.Entity<MyEntity>()
.HasRequired(myEntity => myEntity.MyEntityMyGroup)
.WithOptional(group => group.MyEntity);
means that MyGroup
is the principal and MyEntity
is the dependent with MyEntity.Id
being both PK and FK (the so called "Shared Primary Key Association").
In EF Core the same is expressed with the following fluent configuration:
modelBuilder.Entity<MyEntity>()
.HasOne(myEntity => myEntity.MyEntityMyGroup)
.WithOne(group => group.MyEntity)
.HasForeignKey<MyEntity>(e => e.Id);
The most important is the HasForeignKey
generic type argument, since it tells EF Core which of the two entities is the dependent. And of course mapping the dependent PK property as FK.
For more info, see Relationships topic of the official EF Core documentation.