我在理解表達式和函數的工作方式之間的差異時遇到了一些困難。 這個問題打開了,當有人從改變方法簽名:關於傳遞表達式與函數參數的困惑
public static List<Thing> ThingList(Func<Thing, bool> aWhere)
要
public static List<Thing> ThingList(Expression<Func<Thing, bool>> aWhere)
這打破了我的調用代碼。舊的調用代碼(合作)是這樣的:
...
object y = new object();
Func<Thing, bool> whereFunc = (p) => p == y;
things = ThingManager.ThingList(whereFunc);
新的代碼(不工作)看起來是這樣的:
...
object x = new object();
Expression<Func<Thing, bool>> whereExpr = (p) => p == x;
things = ThingManager.ThingList(whereExpr);
這裏面失敗ThingList(...)上
var query = (from t in context.Things.Where(aWhere)
...
隨着運行時錯誤::利用表達式線
Unable to create a constant value of type 'System.Object'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
這個例子很有意思,但我的猜測是它與本地對象變量x沒有正確「複製」到表達式中有關。
有人可以解釋一般如何處理這種情況,爲什麼Func
工作,但Expression
沒有?
是,它使得它的方式到實體框架。我想我必須做兩個方法,一個用於Expression,另一個用於Func在必要時使用。 – Erix 2012-01-04 14:32:08