How to build a dynamic FROM clause for a LINQ query?

.net, c#, entity-framework-4.1, linq, linq-to-entities

Solution

You can use Expression Trees to build dynamic LINQ queries. Here is an example: http://msdn.microsoft.com/en-us/library/bb882637.aspx

Another approach is to use Dynamic LINQ library: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Both approaches are illustrated here: http://www.codeproject.com/Articles/231706/Dynamic-query-with-Linq

Predicate Builder from this example uses Expression Tree approach.

In general, Dynamic LINQ is easier to implement but Expression Tree is more type-safe.

Problem

I have a standard LINQ query: ``` var list = from x in SomeDataContext.ViewName where //Rest of where clause select x; ``` I would like to know if it is possible to build a dynamic LINQ query so that i can change the `SomeDataContext.ViewName` at runtime. I have about 5 different views, all with the basic columns needed to perform the where clause, but with some different column names for each of other views. So is it possible to build up the query so that i can use the different context at runtime, when needed? Example: ``` public void SomeMethod() { var listA = GetList("DataContext.ViewA"); var listB = GetList("DataContext.ViewB"); var listC = GetList("DataContext.ViewC"); } public List<EntityObject> GetList(string dataContextName) { return (from x in /*HERE I WANT TO USE THE dataContextName*/ where //Rest of where clause select x).ToList(); } ```

Original source