LINQ to Entities不支持调用

Dis*_*ile 7 c# linq-to-entities

LINQ to Entities中有以下查询:

var query = from p in db.Products
            where p.Price > 10M
            select p;
Run Code Online (Sandbox Code Playgroud)

此时查询尚未执行,我想编写一个基于某些条件返回true/false的查询:

return query.Any(p => p.IsInStock &&
               (p.Category == "Beverage" ||
               p.Category == "Other"));
Run Code Online (Sandbox Code Playgroud)

这很好用; 但是,我想从我的代码中重用一些东西.我有很多方法需要根据类别是饮料还是其他来过滤,所以我尝试创建一个委托:

Func<Product, bool> eligibleForDiscount = (product) => product.Category == "Beverage" || product.Category == "Other";
Run Code Online (Sandbox Code Playgroud)

我想用代表替换内联检查:

return query.Any(p => p.IsInStock && eligibleForDiscount(p));
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误,说LINQ to Entities不支持Invoke.为什么我不能将内联代码替换为这样的委托,有什么方法可以通过其他方式实现我的重用?

Cri*_*ole 6

回想一下,引擎盖Linq-to-{DATABASE}只是将IQueryable您生成的内容转换为Sql.

你不能内联这样的代码,因为Invoke(你在调用Funcor 时实际调用的方法Action)没有一致的方法将它转换为sql语句(你可以在那里做任何事情).

那说你可以通过拆分来重用零件:

var query = from p in db.Products
            where p.Price > 10M
            select p;

query = query.Where(p => p.IsInStock);
query = query.Where(p => p.Category == "Beverage" || p.Category == "Other");
return query.Any();
Run Code Online (Sandbox Code Playgroud)

这些都可以放入采用IQueryable<Product>并返回相同(但已过滤)的方法中.然后你可以重用你的内心!