Getting metadata in EF Core: table and column mappings

丶灬走出姿态 提交于 2019-12-19 05:22:03

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/39685271/getting-metadata-in-ef-core-table-and-column-mappings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!