C# 实体框架 - 将表的列名作为字符串数组获取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19704364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity Framework - getting a table's column names as a string array
提问by user982119
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?
如果我首先使用 EF 5 和数据库来生成我的数据库的 .edmx 模型,我如何获取实体列的列表?
using (var db = new ProjectNameContext())
{
// string[] colNames = db.Users.
}
What I'm looking for is colNames[0] == "Id", colNames[1] == "FirstName", etc.
我正在寻找的是 colNames[0] == "Id", colNames[1] == "FirstName" 等。
采纳答案by dav_i
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.
当然,这可以用于任何类型,而不仅仅是 EF 表。
回答by Mark Macneil Bikeio
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