EF 4 Query - Issue with Multiple Parameters

2019-08-23 09:44发布

问题:

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.