Creating a dynamic linq query
- by Bas
I have the following query:
from p in dataContext.Repository<IPerson>()
     join spp1 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp1.PersonId
     join s1 in dataContext.Repository<ISports>() on spp1.SportsId equals s1.Id
     join spp2 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp2.PersonId
     join s2 in dataContext.Repository<ISports>() on spp2.SportsId equals s2.Id
     where s1.Name == "Soccer" && s2.Name == "Tennis"
     select new { p.Id };
It selects all the person who play Soccer and Tennis.
On runtime the user can select other tags to add to the query, for instance: "Hockey". now my question is, how could I dynamically add "Hockey" to the query? If "Hockey" is added to the query, it would look like this:
from p in dataContext.Repository<IPerson>()
     join spp1 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp1.PersonId
     join s1 in dataContext.Repository<ISports>() on spp1.SportsId equals s1.Id
     join spp2 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp2.PersonId
     join s2 in dataContext.Repository<ISports>() on spp2.SportsId equals s2.Id  
     join spp3 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp3.PersonId
     join s3 in dataContext.Repository<ISports>() on spp3.SportsId equals s3.Id
     where s1.Name == "Soccer" && s2.Name == "Tennis" && s3.Name == "Hockey"
     select new { p.Id };
It would be preferable if the query is build up dynamically like:
private void queryTagBuilder(List<string> tags)
{
    IDataContext dataContext = new LinqToSqlContext(new L2S.DataContext());
    foreach(string tag in tags)
    {
        //Build the query?
    }
}
Anyone has an idea on how to set this up correctly?
Thanks in advance!