HelloWorld
HelloWorld

Reputation: 3759

How do I find out if a ClrType is Owned in EF Core?

I'm using DbContext.Model.GetEntityTypes() to inspect the types in my db scheme. How can I know if an IEntityType is not owned (i.e. has its own SQL table). In my DbContext, I will indicate the owned property either by using attributes or by using the Fluent API.

Upvotes: 1

Views: 1602

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205829

How can I know if an IEntityType is not owned (i.e. has its own SQL table)

There are actually two questions here.

The first is

How can I know if an IEntityType is not owned

This one is easy - you use IsOwned extension method. So given IEntityType entityType:

bool isOwned = entityType.IsOwned();

The second is

How can I know if an IEntityType has its own SQL table

This one is more complicated, because whether entity type is owned is not enough to tell that.

First off, table splitting (i.e. sharing table between 2 or more entities) is supported only for one-to-one relationships. However EF Core supports also collections of owned types, which are one-to-many relationship and are mapped to a separate table.

You can detect if entity type is reference owned type (i.e. non collection owned type) with code like this:

var ownership = entityType.FindOwnership();
bool isReferenceOwned = ownership != null && ownership.IsUnique;

Second, even though by default reference owned types are mapped to the same table as the owner, they can be configured to use their own table. These can be excluded as follows (EF Core 3.x):

var ownership = entityType.FindOwnership();
bool isSharedOwned = ownership != null && ownership.IsUnique &&
    ownership.PrincipalEntityType.GetTableName() == entityType.GetTableName();

Third, even though by default regular types are mapped to a separate table, they can be configured to use table splitting. So you need to account for that.

Finally, there is also database inheritance, indicated by the BaseType property. Currently EF Core (3.x) supports only EF Core the table-per-hierarchy (TPH) pattern, so only GetRootType can have own table, but in the future (5.x?) EF Core will support table-per-type (TPT), so all these must be accounted as well.

Shortly, in general it's quite hard to determine which entity type has own table, or more specifically, which entity table name you are supposed to configure "by custom convention" if that's the actual question behind. You need to check all the aforementioned conditions and react accordingly. But if you don't use any of these, !entityType.IsOwned() will be enough.

Upvotes: 7

Related Questions