问题
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