Linq and Sql Null Parameters

When doing queries, sometimes the parameters are null.  If you didn't know already, the way to handle null parameters in a select stored procedure is:

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

If the @CustomerName parameter is null when passed into the stored procedure, the first option hits, which means all the records are returned.  Otherwise, actual processing on the name occurs.  I first encountered this when looking at the ASP.NET profile stored procedures in the ASPNETDB.mdf file.

You can do something similar with LINQ.  For instance, you can query as such:

var data = from c in this.Context.Customers
               where (string.IsNullOrEmpty(customerName) || c.CustomerName == customerName)
               select c;

Or, if you have a series of parameters that check certain parameter types, you can filter by:

var data = from c in this.Context.Customers
               where (isCheckingForCustomerName && c.CustomerName == text)
               || (isCheckingForCity && c.City == text)
               || (isCheckingForState && c.State == text)
               || (isCheckingForAccountNumber && c.AccountNumber.ToString() == text)
               select c;

So you have your options in LINQ to do what you want to do in SQL, without having to write a lot of if statements.

Published Thursday, February 07, 2008 8:31 PM by bmains
Filed under:

Comments

# Link Listing - February 7, 2008

Friday, February 08, 2008 8:19 AM by Christopher Steen

Link Listing - February 7, 2008

# Link Listing - February 7, 2008

Friday, February 08, 2008 8:20 AM by Christopher Steen

MSBuild MSBuild By Example [Via: Greg ] WPF Nukeation Studios reuxables - themes for WPF [Via: rrelyea...

# re: Linq and Sql Null Parameters

Friday, February 29, 2008 9:30 PM by zxevil135

QrtY3u r u crazzy? I told u! I can't read!

# re: Linq and Sql Null Parameters

Saturday, March 01, 2008 4:44 PM by zxevil136

854FrA r u crazzy? I told u! I can't read!

# re: Linq and Sql Null Parameters

Thursday, March 06, 2008 6:19 PM by zxevil134

iWGACH r u crazzy? I told u! I can't read, man!

# re: Linq and Sql Null Parameters

Thursday, March 06, 2008 9:25 PM by zxevil141

dmM6co r u crazzy? I told u! I can't read!

# re: Linq and Sql Null Parameters

Friday, March 07, 2008 3:09 PM by zxevil150

DGktxb r u crazzy? I told u! I can't read!

# re: Linq and Sql Null Parameters

Friday, March 07, 2008 6:13 PM by zxevil151

YheZF0 r u crazzy? I told u! I can't read!

# re: Linq and Sql Null Parameters

Friday, March 07, 2008 9:29 PM by zxevil152

gI86el r u crazzy? I told u! I can't read!