简体   繁体   English

如何将具有属性名称的字符串转换为实体框架存储表达式?

[英]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: 然后我尝试将其传递给Select,如下所示:

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. 但是我遇到了运行时异常,即GetPropValue无法转换为存储表达式,据我了解,但我不知道如何解决它。 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 我在Nuget的System.Linq.Dynamic中找到了使用扩展的解决方案

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx 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: 然后,我可以在Select操作中使用字符串谓词,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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