0

I am rebuilding this website php/mysql into asp.net. I am working on building the main card search form in the header of the page. There is a text input, multiple dropdowns (that all point to different columns) and some conditional search options.

For the mysql version I was able to use conditionals to build a sting containing the query and then execute it.

 //MySql/PHP example
 $query = "SELECT * FROM cards WHERE ";

    //Encounter_set 
if (isset($_GET['Encounter_Set']){
    $query.= "Encounter_Set=:Encounter_Set AND ";
    $queryArray['Encounter_Set'] = $_GET['Encounter_Set'];
}

 //radio statements
switch ($_GET['radio']) {
    case "All":     $query.= "(Title LIKE :terms OR Traits LIKE :terms OR Shadow_Text LIKE :terms OR Text LIKE :terms)";break;
    case "Title":   $query.= "(Title LIKE :terms)";break;
    case "Traits":  $query.= "(Traits LIKE :terms)";break;
    case "Text":    $query.= "(Shadow_Text LIKE :terms OR Text LIKE :terms)"; break;
    default:        $query.= "(Title LIKE :terms OR Traits LIKE :terms OR Shadow_Text LIKE :terms OR Text LIKE :terms)";
}

 //Finally
 $result = $db_con->prepare($query);

How would I go about doing that in LINQ?

Mason240
  • 2,924
  • 3
  • 30
  • 46
  • 1
    LINQ allows you to compose the query. http://stackoverflow.com/questions/11194/conditional-linq-queries – Darren Kopp Dec 15 '12 at 17:21
  • Won't this inital statement: `var logs = from log in context.Logs select log;` will get all the rows from the table? It seems inefficient to start by pulling every row from the table. – Mason240 Dec 15 '12 at 17:24
  • 1
    no, linq is lazy, it doesn't execute the query until you actually attempt to enumerate over the values – Darren Kopp Dec 21 '12 at 04:20

1 Answers1

2
using (var context = new MyDbContext())
{
    IQueryable<Card> query = context.Cards;
    if (!string.IsNullOrEmpty(Encounter_Set))
    {
        query = query.Where(c => c.Encounter_Set == Encounter_Set);
    }
    switch (radio)
    {
        default:
        case "All":
            query = query.Where(c => c.Title.Contains(terms)
                || c.Traits.Contains(terms)
                || c.Shadow_Text.Contains(terms)
                || c.Text.Contains(terms));
            break;
        case "Title":
            query = query.Where(c => c.Title.Contains(terms));
            break;
        case "Traits":
            query = query.Where(c => c.Traits.Contains(terms));
            break;
        case "Text":
            query = query.Where(c => c.Shadow_Text.Contains(terms)
                || c.Text.Contains(terms));
            break;
    }
    // ...
    return query.ToList(); // Execute the query
}
Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138