Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting metadata in EF Core: table and column mappings

Looking to get metadata in EF Core, to work with the mappings of objects & properties to database tables & columns.

These mappings are defined in the DBContext.cs OnModelCreating() method, mapping tables with .ToTable(), and columns via .Property.HasColumnName().

But I don't see this metadata under the Entity Types returned by...

IEnumerable<IEntityType> entityTypes = [dbContext].Model.GetEntityTypes();

Is this metadata available anywhere in EF Core?

like image 479
KarlRKaiser Avatar asked Sep 25 '16 09:09

KarlRKaiser


1 Answers

Is this metadata available anywhere in EF Core?

Yes it is. Just additionally to the properties examine the methods (GetXXX, FindXXX etc.). And pay special attention to Relational() extension methods.

For instance:

foreach (var entityType in dbContext.Model.GetEntityTypes())
{
    var tableName = entityType.Relational().TableName;
    foreach (var propertyType in entityType.GetProperties())
    {
        var columnName = propertyType.Relational().ColumnName;
    }
}

You need to have Microsoft.EntityFrameworkCore.Relational Nuget package installed.

Update (EF Core 3.0+): Relational() provider extensions have been removed and properties have been replaced with direct Get / Set extension methods, so the code for column/table names now is simply

var tableName = entityType.GetTableName();
// ..
var columnName = propertyType.GetColumnName();

Update (EF Core 5.0+): Since now EF Core supports separate column name mappings for table, view, sql etc., you have to pass the desired StoreObjectIdentifier to GetColumnName method, e.g.

var tableName = entityType.GetTableName();
var tableIdentifier = StoreObjectIdentifier.Table(tableName, entityType.GetSchema());
// ...
var tableColumnName = propertyType.GetColumnName(tableIdentifier);
like image 95
Ivan Stoev Avatar answered Sep 28 '22 11:09

Ivan Stoev