配置实体时获取表名 [英] Get the table name when configuring an entity

查看:66
本文介绍了配置实体时获取表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EF核心:我需要获取表的名称作为实体的名称,而不是dbset,而且,我需要 Id "tableName" +".ID" .

EF Core: I need to get the name of the table as the name of the entity, not dbset, also, I need the Id to be "tableName"+"Id".

我有一个 DbSet< Country>国家-我需要表名称 Country Id 列(继承自基本实体)为 CountryId .

I have a DbSet<Country> Countries - I need table name Country and Id column (inherited from base entity) to be CountryId.

我从这个有效的代码开始:

I started with this code that works:

foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
    var builderEntity = modelBuilder.Entity(entity.Name);

    // make table name to be entity name
    builderEntity.ToTable(entity.DisplayName());

    // make Id column name to be tableName+Id
    var idProperty = entity.FindProperty("Id");

    if (idProperty != null)
    {
        builderEntity.Property("Id")
            .HasColumnName(entity.GetTableName() + "Id");
    }
}

但是现在我切换到单独的配置.

but now I switch to individual configuration.

我有以下内容:

public class IdEntityConfiguration<TEntity> : BaseEntityConfiguration<TEntity>
    where TEntity : IdEntity
{
    public override void Configure(EntityTypeBuilder<TEntity> builder)
    {
        base.Configure(builder);
        
        // would be better to have the entity TableName, not the Entity name
        // if one day would not be the same...
        var tableName = typeof(TEntity).Name; 

        builder.Property(p => p.Id)
            .HasColumnName(tableName + "Id");
    }
}

问题:如何在上面的代码中获取配置的 TableName (不是实体名称)?

Question: how to get the configured TableName (not the entity name) in the code above?

基类如下:

public class BaseEntityConfiguration<TEntity> : IEntityTypeConfiguration<TEntity>
    where TEntity : BaseEntity
{
    public virtual void Configure(EntityTypeBuilder<TEntity> builder)
    {
        var entityName = typeof(TEntity).Name; // here is OK, generic class name
        builder.ToTable(entityName);
    }
}

推荐答案

如何在上面的代码中获取配置的TableName(不是实体名称)?

How to get the configured TableName (not the Entity name) in the code above?

var tn = builder.Metadata.GetTableName();

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆