【问题标题】:Get the table name when configuring an entity配置实体时获取表名
【发布时间】:2021-05-05 03:56:30
【问题描述】:

EF Core:我需要获取表的名称作为实体的名称,而不是 dbset,另外,我需要 Id"tableName"+"Id"

我有一个DbSet<Country> Countries - 我需要表名CountryId 列(从基本实体继承)为CountryId

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

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");
    }
}

但现在我切换到个人配置。

我有以下几点:

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(不是实体名)?

基类如下:

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);
    }
}

【问题讨论】:

    标签: c# .net .net-core entity-framework-core ef-core-5.0


    【解决方案1】:

    如何获取上面代码中配置的TableName(不是Entity名)?

    var tn = builder.Metadata.GetTableName();
    

    RelationalEntityTypeExtensions.GetTableName(IEntityType) Method Definition

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-16
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      相关资源
      最近更新 更多