C# 将委托传递给CompiledQuery.Compile方法
尝试将委托C# 将委托传递给CompiledQuery.Compile方法,c#,linq-to-sql,C#,Linq To Sql,尝试将委托System.Func传递给CompiledQuery.Compile方法时,我遇到以下错误 “错误1无法从用法推断方法“System.Data.Linq.CompiledQuery.Compile(System.Linq.Expressions.Expression>)”的类型参数。请尝试显式指定类型参数。” 我不明白为什么我不能传递一个委托而不是LINQ查询表达式 请帮助我解决此问题。()仅在表达式上定义,而不在Func上定义 如果将语句重新编写为 var LINQHolder =
System.Func
传递给CompiledQuery.Compile
方法时,我遇到以下错误
“错误1无法从用法推断方法“System.Data.Linq.CompiledQuery.Compile(System.Linq.Expressions.Expression>)”的类型参数。请尝试显式指定类型参数。”
我不明白为什么我不能传递一个委托而不是LINQ查询表达式
请帮助我解决此问题。()仅在表达式上定义,而不在Func上定义
如果将语句重新编写为
var LINQHolder = GetPreCompiledQuery;
var CompiledLINQHolder = CompiledQuery.Compile(LINQHolder);
?您无法传递委托,因为方法签名指定的是表达式树,而不是委托-就这么简单。它们是两种截然不同的类型 它们的共同点是编译器可以将lambda表达式转换为委托或表达式树,这也是编译最后一段代码的原因。现在,在第一种情况下,您不是这样创建委托的——您实际上使用的是方法组转换。这永远不会创建表达式树 如果要在单独的方法中指定查询,则必须如下所示:
private static Expression<Func<Northwind_LINQtoSQLDataContext,
IQueryable<Customer>>
GetPreCompiledQuery()
{
return db => from cust in db.Customers
where cust.Country == "Germany"
select cust;
}
数据库中cust的私有静态表达式
其中客户国家==“德国”
选择客户;
}
顺便说一句,值得注意的是,对于简单查询,查询表达式通常比使用扩展方法更麻烦。例如,上述内容相当于:
private static Expression<Func<Northwind_LINQtoSQLDataContext,
IQueryable<Customer>>
GetPreCompiledQuery()
{
return db => db.Customers.Where(cust => cust.Country == "Germany");
}
私有静态表达式db.Customers.Where(cust=>cust.Country==“Germany”);
}
这将不会在第一行编译,除了其他之外-隐式类型局部变量的初始化表达式不能是方法组。感谢您的响应。我向LINQHolder定义以及GetPreCompiled方法的返回类型提供了以下内容<代码>**“Expression LINQHolder=GetPreCompiledQuery;”***但现在我遇到了类似“无法将方法组“GetPreCompiledQuery”转换为非委托类型“System.Linq.Expressions.Expression”的错误。是否要调用该方法?”
private static Expression<Func<Northwind_LINQtoSQLDataContext,
IQueryable<Customer>>
GetPreCompiledQuery()
{
return db => from cust in db.Customers
where cust.Country == "Germany"
select cust;
}
private static Expression<Func<Northwind_LINQtoSQLDataContext,
IQueryable<Customer>>
GetPreCompiledQuery()
{
return db => db.Customers.Where(cust => cust.Country == "Germany");
}