Entities: Address
and Market
:
public class Address
{
...
// Navigation properties
public Guid MarketId { get; set; }
public Market Market { get; set; }
}
public class Market
{
...
// Navigation properties
public Guid AddressId { get; set; }
public Address Address { get; set; }
}
Relation rules:
- Each
Market
has anAddress
and aMarket
cannot exist without anAddress
.Address
is required - The user cannot delete an
Address
that belongs to aMarket
- When the user deletes a
Market
, itsAddress
must be deleted automatically
Is it possible to configure the above relation with Entity Framework Core and Fluent API?
I've read about one-to-one relationships with EF Core and I learned that I need to say which entity is the principal and which is the dependent. And I must use Fluent API to do that.
I've tried two approaches:
- Market as principal: with this approach, only rule 3 is valid. I can add a
Market
without anAddress
(breaks the rule 1). An existingMarket
is needed to add anAddress
. And the user can delete theAddress
that belongs to aMarket
(breaks the rule 2).
builder.Entity<Market>()
.HasOne<Address>(m => m.Address)
.WithOne(a => a.Market)
.HasForeignKey<Address>(a => a.MarketId)
.OnDelete(DeleteBehavior.Cascade);
Address
as principal: with this approach, only the rule 3 is broken. The user cannot add aMarket
without anAddress
, in other words, an existingAddress
is needed to add aMarket
. The user cannot delete anAddress
that belongs to aMarket
because on the DeleteBehavior, the relation was set as Restrict. But if the user deletes aMarket
, itsAddress
won't be deleted automatically. The API must handle that.
builder.Entity<Market>()
.HasOne<Address>(m => m.Address)
.WithOne(a => a.Market)
.HasForeignKey<Market>(m => m.AddressId)
.OnDelete(DeleteBehavior.Restrict);
I'm not sure if I've set the relations correctly or if it's just an EF Core limitation. Any help?