简体   繁体   中英

How to convert string with property name to Entity framework storage expression?

I need to select specific columns from DB using string with property name in Entity Framework. I use reflections to be able pass complex properties:

public static Object GetPropValue(this Object obj, String name)
{
    foreach (String part in name.Split('.'))
    {
        if (obj == null) { return null; }

        Type type = obj.GetType();
        PropertyInfo info = type.GetProperty(part);
        if (info == null) { return null; }

        obj = info.GetValue(obj, null);
    }
    return obj;
}

Then I tried to pass this into Select like this:

string propertyName = "ModemStatus.Temperature"  // This is sent in http request
DBContext.MyStatuses.Select(x => x.GetPropValue(propertyName))

But I get runtime exception that GetPropValue can not be converted to storage expression, which I understand but I have no idea how to solve it. Any idea?

EDIT: Return type will always be a collection of doubles

 ICollection<double> values = DBContext.MyStatuses.Select(x => x.GetPropValue(propertyName)) 

I have found the solution using extenstions in System.Linq.Dynamic available at Nuget

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Then I can use string predicate in Select operations like this:

DBContext.MyStatuses.Select("ModemStatus.Temperature");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM