Get field from dynamically/programatically named column name with Entity Framework

c# entity-framework entity-framework-6


I'm searching for a way to programatically or dynamically modify column and field names;


string iLoadProfileValue = "ColumnName";

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

I'll programatically alter the value of iLoadProfileValue. And I want to assign the value of that column to the lastCol variable.

How is it accomplished?

You're welcome.


One more time, THANK YOU to thepirat000 and Dismissile

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);
3/13/2014 1:15:14 PM

Accepted Answer

To obtain a list of properties, utilize reflection. Take a look at System's GetProperties() function. Type.

public PropertyInfo[] GetProperties()

Then, using LINQ, you might locate a property that matches your criteria:

var myEntity = DatabaseFunctions.DatabaseClient
    .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);

If you only care about one property, you can call the method, as thepirat000 noted in the comments.GetProperty(string name) in place ofGetProperties() . If you only care about one property and are not reflecting across all columns in your entity, then this would likely be a more effective method.

3/13/2014 12:30:35 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow