C
C#2y ago
sl8er

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);
3 Replies
JakenVeina
JakenVeina2y ago
sounds like you don't want Address to be an owned type
sl8er
sl8erOP2y ago
Well, I guess I do? I don't need to access Address outside the context of a Customer. I don't really need an identifier for Address. It should have value object semantics. With it being owned, I can hide the fact that there still is an address_id being generated in the underlying table (as required by the One-to-Many relationship between Customer and Address. Otherwise I'd have to specify AddressId in Address?
JakenVeina
JakenVeina2y ago
yeah if EF doesn't support both, then it doesn't support both
Want results from more Discord servers?
Add your server