【问题标题】:Entity Framework - getting a table's column names as a string array实体框架 - 将表的列名作为字符串数组
【发布时间】:2013-10-31 10:45:11
【问题描述】:

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

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

我正在寻找的是 colNames[0] == "Id"、colNames[1] == "FirstName" 等。

【问题讨论】:

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


【解决方案1】:

怎么样:

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

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

【讨论】:

  • 是的,就是这样。谢谢* 10。
  • 这不准确。属性可以通过特定配置映射到与属性名不同的列名,也可以通过约定。
  • 补充@GeorgeMauer 写道:EF 允许以“Id”为后缀的道具自动映射到没有Id 后缀的同名对象,这是实际的列名。因此,如果你有“object Name”和“int NameId”,就会有一个 int 类型的“Name”列,但没有 NameId 列。
  • @davi_i 我如何遍历表格列表并获取表格的列名。我想动态设置表名而不是说 typeof(User)。能做到吗?
  • 这好像是属性名,和列名是一样的吗?
【解决方案2】:
var res = typeof(TableName).GetProperties()
                        .Select(property => property.Name)
                        .ToArray();

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

【讨论】:

  • 能否请您澄清一下,两者之间有什么区别以及后者的不同之处?结果一样吗?
  • 后者会给你列的实际名称,而第一个只会给你属性的名称。因此,如果属性foo 映射到列bar,那么后者将为您提供"bar"。所以后者是问题的实际答案,接受的答案不是。但它需要 EF Core 2.x。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-13
  • 2021-09-13
相关资源
最近更新 更多