![](/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.