The EF Core documentation about One-To-One relations says: "When configuring the relationship with the Fluent API, you use the HasOne
and WithOne
methods." A closer look shows that this configures One-To-ZeroOrOne or ZeroOrOne-To-ZeroOrOne relations depending on whether IsRequired
is used or not. Example:
public class ParentEntity
{
public Int64 Id { get; set; }
public ChildEntity Child { get; set; }
}
public class ChildEntity
{
public Int64 Id { get; set; }
public ParentEntity Parent { get; set; }
}
The derived context class contains:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ParentEntity>().HasOne(p => p.Child).WithOne(d => d.Parent)
.HasForeignKey<ChildEntity>("ParentFk").IsRequired();
}
With this configuration, context.SaveChanges
fails after context.Add(new ChildEntity())
as expected (with SqlException: Cannot insert the value NULL into column 'ParentFk' ...
because of IsRequired
) but succeeds after context.Add(new ParentEntity())
and context.Add(new ChildEntity() { Parent = new ParentEntity() })
, i.e., the ParentEntity-ChildEntity
relation is One-To-ZeroOrOne. In other words: the parent of a child is required, the child of a parent is optional.
Is there a way to configure a "real" One-To-One relation where both ends are required?
Maybe this cannot be enforced within the database. But can it be enforced by EF Core? (BTW: It can be enforced by EF6.)