Home > DeveloperSection > Forums > How to get all optional parameters from SQL Server
Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    November-04-2014 2:46 AM

 C# API(s)  SQL Server  Web 
Ratings:


 1 Reply(s)
 595  View(s)
Rate this:

I am creating a Web API GET (all) method with multiple optional parameters. I'm trying this with 1 parameter first but eventually I want 5 optional parameters. Starting with 1 parameter I have 2 situations: parameter is filled in and parameter is not filled in.

Parameter is filled in

from r in db.requests
where r.status == status
select new Models.Request

Parameter is not filled in

from r in db.requests
select new Models.Request

I can not get both situations to work together so my question is: How can I combine these 2 situations?

Controller

public IEnumerable<Request> Get(string status = "")
    {
        var requests = from r in db.requests
                       //where r.status == status
                       select new Models.Request
                       {
                           ID = r.ID,
                           ...more properties
                           };
            return (IEnumerable<Request>)requests;
    }

Route

protected void Application_Start()
    {
        RouteTable.Routes.MapHttpRoute(
        name: "API Default",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional });
    }


Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    November-04-2014 5:34 AM

Try the following code:

from r in db.requests
where r.status == status || status == ""
select new Models.Request

If status is empty string second part of the expression is true and all items will be returned no matter the value of the first part. Otherwise the first part of the expression filters the result set.


Don't want to miss updates? Please click the below button!

Follow MindStick