Reputation: 3044
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?
Upvotes: 0
Views: 256
Reputation: 89241
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
}
Upvotes: 2