使用PredicateExtensions创建sqlscriptes的一个问题
这是我的逻辑代码:
var predicate = PredicateExtensions.False<Customer>();
predicate = predicate.Or(p => p.CustomerID.Contains("N"));
using (Entities e = new Entities())
{
var r = from p in e.Customer.AsQueryable().Where(predicate.Compile())
select p;
foreach (var _r in r)
Console.WriteLine(_r.CustomerID);
}
然后我使用sql server profiler获取这样的sql脚本:
SELECT
[Extent1].[CustomerID] AS [CustomerID],
[Extent1].[Custname] AS [CustEname],
[Extent1].[Site] AS [DefaultSite],
[Extent1].[Currency] AS [Currency],
[Extent1].[PayTerm] AS [PayTerm],
[Extent1].[BAddr1] AS [BillAddr1],
[Extent1].[BAddr2] AS [BillAddr2],
[Extent1].[BAddr3] AS [BillAddr3],
[Extent1].[BContact] AS [BillContact],
[Extent1].[BTel] AS [BillTel],
[Extent1].[BFax] AS [BillFax],
[Extent1].[BEMail] AS [BillEMail],
[Extent1].[Company] AS [DlvyCompany],
[Extent1].[Addr1] AS [DlvyAddr1],
[Extent1].[Addr2] AS [DlvyAddr2],
[Extent1].[Addr3] AS [DlvyAddr3],
[Extent1].[Contact] AS [DlvyContact],
[Extent1].[Tel] AS [DlvyTel],
[Extent1].[Fax] AS [DlvyFax],
[Extent1].[EMail] AS [DlvyEMail],
[Extent1].[Remark] AS [Remark],
[Extent1].[User] AS [User],
[Extent1].[DT] AS [UpdateDT]
FROM [dbo].[Customer] AS [Extent1]
我从数据库中获取所有数据,但我希望sql脚本末尾有一个条件,意味着获取所有数据但customeid包含N(p => p.CustomerID.Contains("N"))
,我得到了一些错误...... 请给一些积分。谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在
Compile()
方法上。您想要使用的IQueryable
扩展方法需要表达式作为其参数。在您的情况下,调用AsQueryable()
不会执行任何操作,并且IEnumerable
扩展方法Where(Func)
被叫。您想要做的是调用IQueryable
扩展方法Where(Expression>)
来代替。要做到这一点很简单:只需不要调用Compile()
,predicate
已经是一个表达式。另外,您使用查询表达式 (from ...
) 的方式(几乎)不会执行任何操作,因此您可以将其省略:The problem lies in the
Compile()
method. TheIQueryable<T>
extension methods that you want to use require expressions as their arguments. CallingAsQueryable()
doesn't do anything in your case and theIEnumerable<Customer>
extension methodWhere(Func<Customer, bool>)
gets called. What you want to do is to call theIQueryable<Customer>
extension methodWhere(Expression<Func<Customer, bool>>)
instead. To do that is simple: just don't callCompile()
,predicate
is already an expression. Also, the way you use the query expression (from …
) doesn't do (almost) anything, so you can leave it out: