c# - 使用 Entity Framework 从动态/编程命名的列名称中获取字段

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

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

作为:

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

最佳答案

您可以使用反射来获取属性列表。查看 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 在评论中指出的那样,如果您只关心单个属性,则可以调用方法 GetProperty(string name) 而不是 GetProperties()。如果您只关心一个属性,而不反射(reflect)实体中的所有列,这可能会更有效。

关于c# - 使用 Entity Framework 从动态/编程命名的列名称中获取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22377804/

相关文章:

c# - 如何在 C# 中使用 DateTime.Now.Ticks 保持精度

c# - Twilio API 请求限制/限制?

c# - TDD:.NET 遵循 TDD 原则,模拟/不模拟?

.net - EF 6.0.0 - 不从头开始创建数据库

c# - 数据库更新异常 : Which field is causing "String or binary data would be truncated"

c# - 从 C# 或 .cmd 提示符执行 .sh

wpf - 如果我使用 EntityFramework,是否必须在 ViewModel 中引发 PropertyChanged?

c# - 在 LINQ 查询中调用 SQL 用户定义的函数

entity-framework - 对 3 层架构中的数据访问层进行单元测试

c# - 使用 Entity Framework 进行分组查询