Entity Framework - getting a table's column names as a string array

时间秒杀一切 提交于 2019-11-29 00:15:08

问题


If I'm using EF 5 and Database first to generate a .edmx model of my database, how do I get a list of an entity's columns?

using (var db = new ProjectNameContext())
{
    // string[] colNames = db.Users.
}

What I'm looking for is colNames[0] == "Id", colNames[1] == "FirstName", etc.


回答1:


How about:

var names = typeof(User).GetProperties()
                        .Select(property => property.Name)
                        .ToArray();

Of course, this can be used for any type, not just an EF table.




回答2:


var res = typeof(TableName).GetProperties()
                        .Select(property => property.Name)
                        .ToArray();

OR

var res = dbContext.Model.FindEntityType(typeof(TableName))
                           .GetProperties().Select(x => x.Relational().ColumnName)
                           .ToList();

var index = 0;    
var propertyInfo = res[index].PropertyInfo;

var columnName = res[index].Relational().ColumnName;
var propertyName = propertyInfo.Name;
var propertyValue = propertyInfo.GetValue(sourceObject); // NEED OBJECT TO GET VALUE


来源:https://stackoverflow.com/questions/19704364/entity-framework-getting-a-tables-column-names-as-a-string-array

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