简体   繁体   中英

Get namespace of entity class in EF Core model builder

I'm trying to establish a table naming convention such that the table name is a combination of the namespace and class. For example

namespace Sales;

public class Order { }

would translate to a table name of Sales_Order .

I've worked it out for the individual class

builder.ToTable($"{typeof(Order).Namespace}_{typeof(Order).Name}");

I'd like to set this as a default for all tables, if a ToTable was not explicitly set.

protected override void OnModelCreating(ModelBuilder builder)
{
    foreach(var entityType in builder.Model.GetEntityTypes())
    {
        if(entityType.ClrType == null) { continue; }
        {
            string tableName = entityType.GetTableName();
            string tableNamespace = entityType.GetType().Namespace;
            entityType.SetTableName($"{tableNamespace}_{tableName}");
        }
    }
}

but I can't get the namespace of the entity class. It is instead returning Microsoft.EntityFrameworkCore.Metadata.Internal

My entities will be in multiple different class libraries so I'm hoping to intercept and change the name in the model builder.

Any suggestions on how to determine the namespace of the entity from within modelbuilder?

entityType.GetType() is GetType method inherited from object so it will return underlying type for IMutableEntityType (collection of which is returned by builder.Model.GetEntityTypes() ), use entityType.ClrType :

string tableNamespace = entityType.ClrType.Namespace;

Here is the final solution.

protected override void OnModelCreating(ModelBuilder builder)
{
    foreach(var entityType in builder.Model.GetEntityTypes())
    {
        if (entityType.ClrType == null) { continue; }

        string entityName = entityType.Name.Split(".").Last();
        string tableName = entityType.GetTableName();

        if (tableName == entityName)
        {
            entityType.SetTableName($"{entityType.Name.Replace(".", "_")}");
        }

}

If the entity name matches the table name, the convention is applied. If an explicit ToTable was used to apply a different name, the convention is skipped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM