使用表达式来; Func键<>>在LINQ查询 [英] Using Expression<Func<>> in a LINQ Query
问题描述
我要定义一个 Func键< ProductItemVendor,布尔>
过滤 CompareProductItemVendorIds
命名表达式,它可以在整个使用我的应用程序,主要是在实体框架/ LINQ查询。
I want to define a Func<ProductItemVendor, bool>
filter expression named CompareProductItemVendorIds
, which can be used throughout my application, mostly within Entity Framework/LINQ queries.
我已经了解到,为了能在LINQ查询使用此过滤器,我必须声明为表达式来; Func键<>>
,而不是仅仅 Func键<>
。我理解这样做的原因,并很容易为我做到这一点。
I've learned that in order to be able to use this filter in a LINQ query, I must declare it as Expression<Func<>>
instead of just Func<>
. I understand the reason for this, and it's easy for me to do this.
不过,我在用我的查询表达式如下问题。
But I'm having the following problems using that expression in my queries.
首先,这样的代码:
ProductItem.ProductItemVendors.FirstOrDefault(CompareProductItemVendorIds)
的注: ProductItem
是一个数据库实体,其 ProductItemVendors
属性是一个导航集的
Note: ProductItem
is a database entity, and its ProductItemVendors
property is a navigation collection.
产生错误:
`实例参数:无法从'了System.Collections.Generic.ICollection'转换为'System.Linq.IQueryable
`Instance argument: cannot convert from 'System.Collections.Generic.ICollection' to 'System.Linq.IQueryable'
第二,这样的代码:
var results = from v in Repository.Query<ProductItemVendor>()
where CompareProductItemVendorIds(v)
select v;
产生错误:
Produces the error:
CompareProductItemVendorIds'是一个'变量',但使用像一个方法
'CompareProductItemVendorIds' is a 'variable' but is used like a 'method'
所以,我有我漂亮的光泽新的表达式来; Func键<>>
。我如何使用它在我的LINQ查询?
So I have my nice shiny new Expression<Func<>>
. How can I use it in my LINQ queries?
推荐答案
ProductItem
是已经是实体
,所以你不能用你的表情,你需要使用的编译()来获得 Func键<>
从表达式来; Func键<>>
因为ProductItemVendors不再是的IQueryable
ProductItem
is already an Entity
, so you can't use your Expression, you need to use Compile() to get the Func<>
from your Expression<Func<>>
since ProductItemVendors is no longer an IQueryable
ProductItem.ProductItemVendors.FirstOrDefault(CompareProductItemVendorIds.Compile())
您将不得不使用你的表达上ProductItemVendorsContext是这样的:
You would have to use your Expression on the ProductItemVendorsContext like this:
var item = Context.ProductItemVendors.FirstOrDefault(CompareProductItemVendorIds);
您不能使用查询语法内的表达,你需要使用方法sytanx
You cant use an Expression inside query syntax, you need to use method sytanx
var results = from v in Repository.Query<ProductItemVendor>()
.Where(CompareProductItemVendorIds)
select v;
这篇关于使用表达式来; Func键<>>在LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!