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?