簡體   English   中英

如何將具有屬性名稱的字符串轉換為實體框架存儲表達式?

[英]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中找到了使用擴展的解決方案

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

然后,我可以在Select操作中使用字符串謂詞,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM