Getting metadata in EF Core: mapping tables and columns

Look for metadata in EF Core to work with object and property mappings with database tables and columns.

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

But I do not see this metadata under the types of objects returned ...

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

Is this metadata available anywhere in the EF Core?

+10
source share
1 answer

Is this metadata available in EF Core?

Yes it. Just study the methods in addition to the properties ( GetXXX , FindXXX , etc.). And pay particular attention to the extension methods of Relational() .

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 must have the Microsoft.EntityFrameworkCore.Relational Nuget package installed.

Update (EF Core 3. 0+): Relational() provider extensions were removed and the properties were replaced with direct Get / Set extension methods, so the code for the column / table names is now simple

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

All Articles