实体框架 - 将表的列名称作为字符串数组

时间:2013-10-31 10:45:12

标签: c# linq entity-framework entity-framework-5

如果我首先使用EF 5和数据库生成数据库的.edmx模型,如何获取实体列的列表?

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

我正在寻找的是colNames [0] ==“Id”,colNames [1] ==“FirstName”等。

2 个答案:

答案 0 :(得分:40)

怎么样:

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

当然,这可以用于任何类型,而不仅仅是EF表。

答案 1 :(得分:1)

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