的部分跳出LINQ2SQL表達
private static void Original()
{
using (var context = new AdventureWorksContext())
{
var result =
from product in context.Products
from workorder in product.WorkOrders
select new
{
productName = product.Name,
order = workorder,
};
var result2 =
from item in result
where item.order.WorkOrderRoutings.Count() == 1
select item.productName;
foreach (var item in result2.Take(10))
{
Console.WriteLine(item);
}
}
}
我想打出來的item.order.WorkOrderRoutings.Count()
一部分,並與基於某些輸入參數別的東西,像item.order.OrderQty
取代我有這段代碼LINQ。
我第一次嘗試:
private static Func<WorkOrder, int> GetRoutingCountFunc()
{
return workOrder => workOrder.WorkOrderRoutings.Count();
}
private static void RefactoredFunc()
{
using (var context = new AdventureWorksContext())
{
var result =
from product in context.Products
from workorder in product.WorkOrders
select new
{
productName = product.Name,
order = workorder,
};
var result2 =
from item in result
where GetRoutingCountFunc()(item.order) == 1
select item.productName;
foreach (var item in result2.Take(10))
{
Console.WriteLine(item);
}
}
}
當然
失敗,運行時有異常
Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL.
所以我想通了,我需要把某種Expression
。最合理的我可以找出是
private static Expression<Func<WorkOrder, int>> GetRoutingCountExpression()
{
return workOrder => workOrder.WorkOrderRoutings.Count();
}
private static void RefactoredExpression()
{
using (var context = new AdventureWorksContext())
{
var result =
from product in context.Products
from workorder in product.WorkOrders
select new
{
productName = product.Name,
order = workorder,
};
var result2 =
from item in result
where GetRoutingCountExpression()(item.order) == 0
select item.productName;
foreach (var item in result2.Take(10))
{
Console.WriteLine(item);
}
}
}
但是,讓一個編譯時錯誤:「方法名稱預期」就行了where GetRoutingCountExpression()(item.order) == 0
。
如果不是匿名類型,我可以創建一個方法返回Expression<Func<"anonType", bool>>
並將其用作where參數。
如何分解部分LINQ表達式?
http://www.albahari.com /nutshell/predicatebuilder.aspx你可以試試這個方向 –
+1爲Adrian Iftodes回答。我有完全相同的問題,並最終使用瞭解決我的問題的謂詞構建器。 – wasatz