EF Core column name from mapping api

纵饮孤独 提交于 2020-01-11 06:18:07

问题


In EF 6.1 the mapping API was introduced where we could finally get access to table names and column names. Getting the table name is a very nice change in EF Core, but I have not yet uncovered how to get the column names.

For anyone interested here is how I got the table name in the latest version (RC1)

context.Model.FindEntityType(typeof(T)).SqlServer().TableName

What is the current method to get column names or is this not available yet?


回答1:


var columnNames = ctx.Model.FindEntityType(typeof (T))
                           .GetProperties().Select(x => x.SqlServer().ColumnName)
                           .ToList();

Also

var columnNames = ctx.Model.FindEntityType(typeof (T))
                           .GetProperties().Select(x => x.Relational().ColumnName)
                           .ToList();

In EF Core 3.X, .Relational() and .SqlServer() have been replaced and you can simply use:

var columnNames = ctx.Model.FindEntityType(typeof (T))
                           .GetProperties().Select(x => x.GetColumnName())
                           .ToList();



回答2:


This version doesn't assume SqlServer and can work as well with Npgsql provider as long as data store is relational.

var columnNames = dbContext.Model.FindEntityType(typeof(T))
                  .GetProperties().Select(x => x.Relational().ColumnName);


来源:https://stackoverflow.com/questions/35124306/ef-core-column-name-from-mapping-api

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