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

Erç*_*ğlu 3 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;
Run Code Online (Sandbox Code Playgroud)

我将以编程方式更改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);
}
Run Code Online (Sandbox Code Playgroud)

Dis*_*ile 6

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

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

public PropertyInfo[] GetProperties()
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)

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