简体   繁体   English

转换表名(以字符串形式)以在LINQ查询中使用它:C#,实体框架

[英]Convert table name (in string) to use it in the LINQ query : C#, Entity Framework

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: 我想遍历列表并在LINQ查询中使用表名:

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 遍历表名称,并为每个名称执行LINQ查询,如下所示

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. 在上面的语句中,“ from table中的t”无效,因为“ table”是字符串。 I need actual table object reference to use. 我需要使用实际的表对象引用。

Need help on how do I go about doing that. 需要帮助我如何去做。

You can use the DbContext.Set method: 您可以使用DbContext.Set方法:

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

Above sentence will return a non generic DbSet. 上面的句子将返回一个非通用的DbSet。 So, you will not be able to query with linq as usual. 因此,您将无法照常使用linq进行查询。 But you can use dynamic linq. 但是您可以使用动态linq。 ScottGu will explain it better than me . ScottGu 将比我更好地解释它 Please, check this thread for other solutions. 请检查此线程以获取其他解决方案。

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 select, where, from是定义LINQ的一种方法,但是如果您具有元素列表(例如IEnumerable<T> ),则可以使用它,但是只有表名

I think You have to create a regular SQL query 我认为您必须创建一个常规的SQL查询

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 在EF中,您可以执行常规查询

In EF you can execute SQL Code . EF中,您可以执行SQL代码

In this example i use EF with SQL ( String ) 在此示例中,我将EF与SQL( String )一起使用

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



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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM