我想創建一個使用LINQ to Entities w/EF5的動態字段。基於某些條件(我將其封裝在函數中),動態字段將填充不同的值。LINQ to Entities創建動態字段
我引用的帖子here但是當我運行下面的代碼,我得到了如下錯誤:
LINQ到實體無法識別方法「System.String FORMATNAME()」方法,而這種方法不能被翻譯成商店表達。
public static IEnumerable<dynamic> SelectAllCustomers()
{
using (var db = new DatabaseContext())
{
var query = db.Customer.Select(c => new
{
c.ID,
FullNameLastFirstMiddle = FormatName(c.First_Name, c.Middle_Name, c.Last_Name),
}
);
return query.ToList();
}
}
private static string FormatName(string first, string middle, string last)
{
//format name
if (!String.IsNullOrWhiteSpace(first))
{
if (!String.IsNullOrWhiteSpace(middle))
return last + ", " + first + " " + middle;
else
return last + ", " + first;
}
else
{
if (!String.IsNullOrWhiteSpace(middle))
return last + ", " + middle;
else
return last;
}
}
就如何更好地動態建立使用LINQ到實體sofisticated邏輯字段的任何想法?
你必須把它內聯寫,作爲查詢的一部分,使用':'運營商。 – MarcinJuraszek
也許更好的辦法是總是從數據庫中單獨提取這些字段,並在需要時執行該邏輯的代碼中添加一個額外的屬性或方法。 – Silvermind
@MarcinJuraszek邏輯是相當複雜的,所以我正在尋找一個解決方案,我可以在方法調用中進行封裝。這[後](http://stackoverflow.com/questions/13880630/im-trying-to-create-a-dynamic-object-based-on-the-val-of-a-column-using-linq)有一個方法調用作爲查詢的一部分,但是當我嘗試實現這個設計時,我得到了OP中提到的異常。 –