Getting metadata in EF Core: table and column mappings

后端 未结 1 766
盖世英雄少女心
盖世英雄少女心 2020-12-10 11:49

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 DBConte

相关标签:
1条回答
  • 2020-12-10 12:25

    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();
    
    0 讨论(0)
提交回复
热议问题