I am trying to write one linq to sql query and dynamically choose which table to select from at runtime based on an input string provided by the user. Right now I have a selection statement that does this but it just repeats the same query three times, only difference being the selected table. Kinda like this:
if (input == "94")
{
var query = from i in db.Table94
select new MyClass(i.A, i.B, i.C);
}
if (input == "95")
{
var query = from i in db.Table95
select new MyClass(i.A, i.B, i.C);
}
//more conditional queries
query = query.Where(addtionalFilteringDoneHere);
DataGridView.DataSource = query;
It is easy enough to use conditional Where clauses, but I am looking for something similar for table selections. I tired a couple of things but they didn’t work. Something like:
var query = from i in FetchTable(input)
select new MyClass(i.A, i.B, i.C);
query = query.Where(addtionalFilteringDoneHere);
public returnType FetchTable(string input)
{
//need help here
return db.GetTable<conditionalTable>;
}
I don’t know what the return type would be or even if there a way to do this. Is it possible?
Since you’re trying to create
MyClassinstances from different tables you’ve got a problem of either creating a dynamic query – which means you throw out EF or LINQ-to-SQL – or you do a basic lookup instead.I would suggest the basic lookup and that you do something like this:
This creates a strongly-typed query within a general purpose dictionary that you can now easily pull out your
MyClassinstances.Something like this:
You could use
fetch[input].Invoke(db)if you like that syntax better.How does this look as a solution?