Dynamic LINQ queries for a web API

asp.net-web-api c# dynamic entity-framework-6 linq

Question

public JsonResult GetThis(string typ1)
{     
    ThisContext tpc = new ThisContext();
    IQueryable<ThisDB> oDataQuery = tpc.ThisDBs;
    if (typ1 != null)
    {
        oDataQuery = oDataQuery.Where(a => a.Type == typ1);
        var result = oDataQuery.ToList();
        return Json(result, JsonRequestBehavior.AllowGet);
    }
    else return null;
}

The idea here is to create a basic get method that select every rows with the 'good' Type, it's nothing less than a web API method.

The problem is that I don't see why my code is not working, it actually returns nothing ( the database is not empty and if I query it without parameter it's working smoothly ).

This must be a stupid mistake but I can't see it. I know that there is multiple ways to do a dynamic linq query but I'd like first to understand why this is not working.

Thank you for your time !

1
2
3/30/2016 3:27:48 AM

Popular Answer

First thing, you should be defining a scope for Database context since it's disposable.(Though it won't affect the result set but it's a good practice)

 using(ThisContext tpc = new ThisContext())
 {
      //Your code goes here.
 }

Next thing is, you should use

string.IsNullOrEmpty() 
//or 
string.IsNullOrWhiteSpaces()

method available to check if the string is empty or it may contain content as white-spaces or empty string.

public JsonResult GetThis(string typ1)
{     
    using(ThisContext tpc = new ThisContext())
    {
        IQueryable<ThisDB> oDataQuery = tpc.ThisDBs;
        if (!string.IsNullOrWhiteSpace(typ1))
        {
            oDataQuery = oDataQuery.Where(a => a.Type == typ1);
            var result = oDataQuery.ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        else return null;
    }
}
0
3/28/2016 6:19:52 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow