serge
serge

Reputation: 15229

Get the table name when configuring an entity

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

Upvotes: 3

Views: 1606

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89026

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

var tn = builder.Metadata.GetTableName();

RelationalEntityTypeExtensions.GetTableName(IEntityType) Method Definition

Upvotes: 4

Related Questions