Get the table name when configuring an entity

孤街浪徒 提交于 2021-02-08 11:35:59

问题


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".

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.

I have the following:

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

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

The base class is the following:

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

回答1:


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

var tn = builder.Metadata.GetTableName();

RelationalEntityTypeExtensions.GetTableName(IEntityType) Method Definition



来源:https://stackoverflow.com/questions/65984820/get-the-table-name-when-configuring-an-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!