EF 4 Query - Issue with Multiple Parameters

ⅰ亾dé卋堺 提交于 2020-01-16 12:30:13

问题


A trick to avoiding filtering by nullable parameters in SQL was something like the following:

select * from customers where (@CustomerName is null or CustomerName = @CustomerName)

This worked well for me in LINQ to SQL:

string customerName = "XYZ";
var results =
   (from c in ctx.Customers 
    where (customerName == null || (customerName != null && c.CustomerName == customerName)) 
    select c);

But that above query, when in ADO.NET EF, doesn't work for me; it should filter by customer name because it exists, but it doesn't. Instead, it's querying all the customer records. Now, this is a simplified example, because I have many fields that I'm utilizing this kind of logic with. But it never actually filters, queries all the records, and causes a timeout exception. But the wierd thing is another query does something similarly, with no issues.

Any ideas why? Seems like a bug to me, or is there a workaround for this? I've since switched to extension methods which works.

Thanks.


回答1:


Have you tried it with a ternary operator in the where clause?

where (customerName == null ? true : c.CustomerName == customerName)



回答2:


I still didn't figure it out, but rewriting it as a proc fixed the issue, so that was my workaround, as bad as that is.



来源:https://stackoverflow.com/questions/4125512/ef-4-query-issue-with-multiple-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!