【发布时间】:2021-05-05 03:56:30
【问题描述】:
EF Core:我需要获取表的名称作为实体的名称,而不是 dbset,另外,我需要 Id 为 "tableName"+"Id"。
我有一个DbSet<Country> Countries - 我需要表名Country 和Id 列(从基本实体继承)为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