配置实体时获取表名 [英] Get the table name when configuring an entity
问题描述
EF Core:我需要将表的名称作为实体的名称,而不是 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
和 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();
RelationalEntityTypeExtensions.GetTableName(IEntityType) 方法定义
这篇关于配置实体时获取表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!