【问题标题】:Get field from dynamically/programatically named column name with Entity Framework使用实体框架从动态/编程命名的列名中获取字段
【发布时间】:2014-03-13 21:15:14
【问题描述】:

我正在寻找一种以动态/编程方式更改列和字段名称的方法;

作为:

string iLoadProfileValue = "ColumnName";

string lastCol = DatabaseFunctions.DatabaseClient
.tbl_MeterLoadProfile
.OrderByDescending(a => a.MeterReadDate)
.FirstOrDefault(a => a.MeterID == meterID).iLoadProfileValue;

我将以编程方式更改 iLoadProfileValue 的值。 我想将该列的值设为 lastCol 变量。

怎么做?

非常感谢。

完成:

最后的情况是这样的: 感谢 thepirat000Dismissile

string iLoadProfileValue = "MeterReadDate";
var myEntity = DatabaseFunctions.DatabaseClient.tbl_MeterLoadProfile.OrderByDescending(a => a.MeterReadDate).FirstOrDefault(a => a.MeterID == 6);

if (myEntity != null)
{
    var properties = myEntity.GetType().GetProperty(iLoadProfileValue);
    object value = properties.GetValue(myEntity);
}

【问题讨论】:

  • 为什么要在 iLoadProfileValue 上使用 i 前缀?只是问问。
  • 这是个坏习惯 :)。以 i 开头通常意味着该变量是一个 int。
  • :) 感谢您的警告,我会注意到的

标签: c# entity-framework entity-framework-6


【解决方案1】:

您可以使用反射来获取属性列表。查看 System.Type 上的 GetProperties() 方法。

http://msdn.microsoft.com/en-us/library/aky14axb(v=vs.110).aspx

public PropertyInfo[] GetProperties()

然后您可以使用 LINQ 查找与您想要的属性匹配的属性:

var myEntity = DatabaseFunctions.DatabaseClient
    .tbl_MeterLoadProfile
    .OrderByDescending(a => a.MeterReadDate)
    .FirstOrDefault(a => a.MeterID == meterID);

if(myEntity != null) {
    var properties = myEntity.GetType().GetProperties();

    // iterate through the list of public properties or query to find the one you want
    // for this example I will just get the first property, and use it to get the value:
    var firstProperty = properties.FirstOrDefault();

    // get the value, it will be an object so you might need to cast it
    object value = firstProperty.GetValue(myEntity);
}

正如 thepirat000 在 cmets 中指出的那样,如果您只关心单个属性,则可以调用方法 GetProperty(string name) 而不是 GetProperties()。如果您只关心一个属性,而不是反映实体中的所有列,这可能会更有效。

【讨论】:

  • 感谢您的快速响应。 prntscr.com/30ej8f我试过了,得到了这样的结果。如何动态选择变量值?
  • PropertyInfo 有一个名为 GetValue(object) 的方法,该方法将您要为其获取值的实例作为其参数。我编辑了帖子以显示这一点。 msdn.microsoft.com/en-us/library/hh194385(v=vs.110).aspx
  • 你可能不需要用GetProperties()获取所有属性,你可以调用GetProperty(iLoadProfileValue)来获取属性.
  • @thepirat000 很好的建议。如果他想在一个循环中获取所有属性,那么使用 GetProperties 可能是有意义的,否则如果您只需要一个属性,那么 GetProperty 会更有意义。
  • 非常感谢你们俩
猜你喜欢
  • 2014-04-18
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多