2

I can build the WHERE clause with a varying number of "AND"s in a string in PHP and then concatenate it to the end of my SELECT statement before running. I am trying to figure out how to do this in MVC Controller ActionResult event using LINQ

Usually something like

var strSQL ="SELECT field1, field3, field5 FROM tblWhatever WHERE 1-1"

(the 1=1 allows flexibilty in how many AND's I build, not having to worry about the first one)

then I build the string of ANDs or just one and concatenate

strSQL .= " AND DWPCEU != null "
strSQL .=" AND DEQCEU !=null "

then I run the SQL (in PHP)

Got any idea how I would build a string of ANDs in a Controller ActionResult?

this limited example below works, but only for one AND. I know I can add "&&"s ad nauseum but would rather build it elsewhere since there are 4x4 number of checkbox choices. There are 4 checkboxes and none, any, or all can be checked.

var courses = from m in _db.Courses select m;

if (!String.IsNullOrEmpty(searchString))
{
    if (bolDWP == true)
    {
        courses = courses.Where(s => s.CourseTitle.Contains(searchString) **&& s.CEUDWP !=null**);
    }
    else
    {
        courses = courses.Where(s => s.CourseTitle.Contains(searchString));
    }
}
Halvor Holsten Strand
  • 19,829
  • 17
  • 83
  • 99
JustJohn
  • 1,362
  • 2
  • 22
  • 44
  • You can continue to chain together as many `.Where()` as you want, and it will perform the conversion to all of the "AND"s as you want. – krillgar Jul 24 '14 at 17:24

1 Answers1

2

I'm guessing you want to do something like this:

    var courses = _db.Courses.AsQueryable();

    if (!String.IsNullOrEmpty(searchString))
    {
        courses = courses.Where(s => s.CourseTitle.Contains(searchString));
    }
    if (bolDEQ)
    {
        courses = courses.Where(s => s.CEUDEQ != null);
    }
    if (bolDWP)
    {
        courses = courses.Where(s => s.CEUDWP != null);
    }
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • Yes! You beat me to answering my own question thank you very much! Found this explanation: "Since LINQ uses deferred execution, chaining .Where into your queries works fine, and still only executes once on the server (with the filters you specify)" – JustJohn Jul 24 '14 at 18:55