C# 使用实体框架从动态/编程命名的列名中获取字段

C# 使用实体框架从动态/编程命名的列名中获取字段,c#,entity-framework,entity-framework-6,C#,Entity Framework,Entity Framework 6,我正在寻找一种方法来动态/编程地更改列名和字段名 as: string iLoadProfileValue = "ColumnName"; string lastCol = DatabaseFunctions.DatabaseClient .tbl_MeterLoadProfile .OrderByDescending(a => a.MeterReadDate) .FirstOrDefault(a => a.MeterID == meterID).iLoadProfileValue

我正在寻找一种方法来动态/编程地更改列名和字段名

as:

string iLoadProfileValue = "ColumnName";

string lastCol = DatabaseFunctions.DatabaseClient
.tbl_MeterLoadProfile
.OrderByDescending(a => a.MeterReadDate)
.FirstOrDefault(a => a.MeterID == meterID).iLoadProfileValue;
我将以编程方式更改iLoadProfileValue的值。 我想将该列的值设置为lastCol变量

怎样才能做到呢

非常感谢

完成:

string iLoadProfileValue = "ColumnName";

string lastCol = DatabaseFunctions.DatabaseClient
.tbl_MeterLoadProfile
.OrderByDescending(a => a.MeterReadDate)
.FirstOrDefault(a => a.MeterID == meterID).iLoadProfileValue;
最后一种情况是: 多亏了Pirat000和解雇

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()方法

然后,您可以使用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);
}

正如Pirat000在注释中指出的那样,如果只关心单个属性,则可以调用方法
GetProperty(字符串名称)
,而不是
GetProperties()
。如果您只关心一个属性,而不是反映实体中的所有列,那么这可能会更有效。

感谢您的快速响应。我试过了,结果变成了这样。如何使用变量进行数值选择?PropertyInfo有一个名为GetValue(object)的方法,该方法将要获取其值的实例作为其参数。我编辑了这篇文章来展示这一点。您可能不需要使用GetProperties()获取所有属性,只需调用GetProperty(iLoadProfileValue)即可获取属性。@thepirat000非常好的建议。如果他想在一个循环中获取所有属性,那么使用GetProperties可能是有意义的,否则如果您只需要一个属性,那么GetProperty就更有意义了。非常感谢你们两位为什么在iLoadProfileValue?上使用i前缀?。只是问问而已。这是个坏习惯:)。从i开始通常意味着变量是一个int.:)谢谢你的警告,我会注意到你能看一下吗?