Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL - Ignore search parameters that are null or zero

I have a search form where the user can enter one to many parameters (Data, Status, Type, ID, Summary, Description) and leave the rest blank.

Here's my Linq to SQL code for my basic search. Is there a way to check each parameter within the Linq for zero, null or empty string?

List<RequestStatusModel> objRequestStatus = new List<RequestStatusModel>();
var query = from r in SimCareDB.Requests
            where r.CustomerID == 31       
            select (new RequestStatusModel
            {
                RequestID = r.RequestID,
                RequestTitle = r.RequestTitle,
                DateAdded = r.DateAdded.ToString(),
                DateChanged = r.DateChanged.ToString(),
                RequestStatusID = r.StatusID
            });

Thank you!

like image 616
Simon Avatar asked Apr 06 '16 13:04

Simon


1 Answers

If it doesn't have to be in your linq statement you could just do it with classic if statements.

List<RequestStatusModel> objRequestStatus = new List<RequestStatusModel>();
var query = from r in SimCareDB.Requests
            where r.CustomerID == 31
            select (new RequestStatusModel
            {
               //...
            });

if(data != null) //Replace with additional checks, if neccessary
{
   query = query.where(x=> ...);
}

if(status != null) 
{
   query = query.where(x => ...)
}
like image 76
Marco Avatar answered Nov 15 '22 00:11

Marco