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



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

AS:

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

我将通过程序上更改 ILOADPROFILEVALUE 的值。我想将该列的值降至 lastCol variable。

如何完成?

非常感谢。

完成:

这样的最后情况:感谢 thepirat000 dimplile

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()。如果您只关心一个属性,并且您没有反映实体中的所有列,这可能会更有效。

最新更新