![](/img/trans.png)
[英]Entity Framework 4: convert a string condition to a lambda expression?
[英]How to convert string with property name to Entity framework storage expression?
我需要使用实体框架中带有属性名称的字符串从数据库中选择特定的列。 我使用反射来传递复杂的属性:
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;
}
然后我尝试将其传递给Select,如下所示:
string propertyName = "ModemStatus.Temperature" // This is sent in http request
DBContext.MyStatuses.Select(x => x.GetPropValue(propertyName))
但是我遇到了运行时异常,即GetPropValue无法转换为存储表达式,据我了解,但我不知道如何解决它。 任何想法?
编辑:返回类型将始终是双打的集合
ICollection<double> values = DBContext.MyStatuses.Select(x => x.GetPropValue(propertyName))
我在Nuget的System.Linq.Dynamic中找到了使用扩展的解决方案
然后,我可以在Select操作中使用字符串谓词,如下所示:
DBContext.MyStatuses.Select("ModemStatus.Temperature");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.