public class Command
{
public int CommandId { get; set; }
public string Title { get; set; }
public virtual ICollection<CommandPart> CommandParts { get; set; }
}
public class CommandPart
{
public int CommandPartID { get; set; }
public string part { get; set; }
public virtual ICollection<Command> command { get; set; }
}
public ViewResult Filter(string myString)
{
var foo = myString.Split(Convert.ToChar("+"));
var a = foo[0];
var b = foo[1];
var query =
db.Commands.Where(
c =>
c.CommandParts.Any(p => p.part == a)
&& (c.CommandParts.Any(p2 => p2.part == b))).ToList();
return View(query.ToList());
}
The query above works as expected when there are exactly two items in foo. I would like to be able to loop over foo to create the query. Here is my attempt, but it is not working:
var foo = myString.Split(Convert.ToChar("+"));
IQueryable<Command> query = db.Commands;
foreach (var keyword in foo)
{
query = query.Where(c => c.CommandParts.Any(p => p.part == keyword));
}
This is an ASP.NET MVC3 project using Entity Framework. How can I write the query so that it is generated at runtime?
Look at PredicateBuilder. It’s a small helper class that encapsulates some LINQ Expressions that allow you to dynamically build up your
Wherepredicate clause. You can AND and OR clauses together, and nest them pretty deep.So you could do something like this (pseudo-code):
I missed that you’re using EF, so you’ll need to download LINQKit (a NuGet that you can download, too), and use its ‘AsExandable’ extension. See the PredicateBuilder page about this (about half-way down).
Hope this helps!