简体   繁体   English

在 EF Core model 构建器中获取实体 class 的命名空间

[英]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.我正在尝试建立一个表命名约定,以便表名是命名空间和 class 的组合。 For example例如

namespace Sales;

public class Order { }

would translate to a table name of Sales_Order .将转换为Sales_Order的表名。

I've worked it out for the individual class我已经为个人 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.如果未明确设置ToTable ,我想将此设置为所有表的默认值。

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.但我无法获得实体 class 的命名空间。 It is instead returning Microsoft.EntityFrameworkCore.Metadata.Internal相反,它返回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.我的实体将位于多个不同的 class 库中,因此我希望在 model 构建器中拦截并更改名称。

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 : entityType.GetType()是从object继承的GetType方法,因此它将返回IMutableEntityType的基础类型(其集合由builder.Model.GetEntityTypes()返回),使用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.如果使用显式ToTable来应用不同的名称,则会跳过约定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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