0

I have a list of table names in form of strings. I want to loop through the list and use the table name in the LINQ query:

var db = new SomeContext();

// for a single table I can use the LINQ query as
var res = from q in db.Table
          where ......
          select q;

and it works just fine.

The above approach is hard coding. I need a generic solution for this to loop through multiple tables whose names are stored in a list.

// list of string containing table names
List<stringtableNames = [Get the table list from some source]
// not a problem here

loop through the table names and for each name execute a LINQ query as shown below

foreach(string table in tableNames)
{ 
    var queryRes = from t in table
                   where <some_condition>
                   select t; 
}

In the above statements "from t in table" above is not valid as "table" is a string. I need actual table object reference to use.

Need help on how do I go about doing that.

3
  • 1
    I thing You have to create a regular SQL query "select * from " + table + "where ..." in EF You can execute regular query Commented Jan 26, 2016 at 8:18
  • 1
    Does tables have same models ? If not its hard to get a result as entity model. Commented Jan 26, 2016 at 8:22
  • Well, what do you expect such a method to return? Obviously it can only return an object as you cannot provide the actual data-type nor even the table itself at compile-time. So I think you´re left on some kind of Sql-script where you set the table-name based on the string. Commented Jan 26, 2016 at 8:22

3 Answers 3

1

You can use the DbContext.Set method:

Set(System.Type.GetType("TableName"))

Above sentence will return a non generic DbSet. So, you will not be able to query with linq as usual. But you can use dynamic linq. ScottGu will explain it better than me. Please, check this thread for other solutions.

Sign up to request clarification or add additional context in comments.

Comments

0

In EF you can execute SQL Code.

In this example i use EF with SQL (String)

var db = new SomeContext();
var list = db.ExecuteStoreQuery<Obj>(Obj.sql);



class Obj
{
   public const string sql = @"select [tbl].[field] from [tbl]";
}

Comments

0

select, where, from is one way to define LINQ but You can use it if you have a list of elements (IEnumerable<T> for example), but You have only name of Your table

I think You have to create a regular SQL query

foreach(string table in tableNames)
{ 
  var query =$"select * from  {table} where <some_condition>"; 
  var list = db.ExecuteStoreQuery<Obj>(query);
}

In EF You can execute regular query

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.