sl8er
sl8er
CC#
Created by sl8er on 5/27/2023 in #help
EF Core Many-to-One (Many Owned Entity to Non-owned Entity)
In the context of a multi-tenant application, I want to design an aggregate like so - a root Customer has a List<Address>, Address being an owned type. A Customer also references a Tenant. If I also want Address to reference a Tenant, it seems EF Core isn't happy when trying to configure a Tenant like so:
// This is fine.
builder
.HasMany<Customer>()
.WithOne(x => x.Tenant)
.HasForeignKey("tenant_id")
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);

// This throws - System.InvalidOperationException: The entity type 'Address' cannot be configured as non-owned because it has already been configured as a owned. Use the nested builder in `OwnsOne` or `OwnsMany` on the owner entity type builder to further configure this type. If you want to override previous configuration first remove the entity type from the model by calling 'Ignore'.
builder
.HasMany<Address>()
.WithOne(x => x.Tenant)
.HasForeignKey("tenant_id")
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
// This is fine.
builder
.HasMany<Customer>()
.WithOne(x => x.Tenant)
.HasForeignKey("tenant_id")
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);

// This throws - System.InvalidOperationException: The entity type 'Address' cannot be configured as non-owned because it has already been configured as a owned. Use the nested builder in `OwnsOne` or `OwnsMany` on the owner entity type builder to further configure this type. If you want to override previous configuration first remove the entity type from the model by calling 'Ignore'.
builder
.HasMany<Address>()
.WithOne(x => x.Tenant)
.HasForeignKey("tenant_id")
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
6 replies