【问题标题】:Dynamic Table Names in Linq to SQLLinq to SQL 中的动态表名
【发布时间】:2010-10-07 07:36:07
【问题描述】:

大家好,我必须使用一个可怕的数据库,而 linq to sql 是我从中检索数据的选项。我试图通过根据用户选择输入不同的表名来重用函数的任何人,据我所知,没有办法在 DataContext 查询中修改 TEntity 或 Table。

这是我当前的代码。

public void GetRecordsByTableName(string table_name){

string sql = "Select * from " + table_name;
var records = dataContext.ExecuteQuery</*Suppossed Table Name*/>(sql);

ViewData["recordsByTableName"] = records.ToList();
}

我想用 Enumerable 记录填充我的 ViewData。

【问题讨论】:

    标签: sql linq-to-sql dynamic ienumerable


    【解决方案1】:

    您可以在 DataContext 实例上调用 ExecuteQuery 方法。您将需要调用采用 Type 实例的重载,如下所示:

    http://msdn.microsoft.com/en-us/library/bb534292.aspx

    假设您有一个为表正确归因的类型,为该类型传递该类型实例,SQL 将为您提供您想要的。

    【讨论】:

      【解决方案2】:

      正如 casperOne 已经回答的那样,您可以使用ExecuteQuery 方法第一个重载(要求输入类型参数的方法)。由于我有类似的问题,并且您问了一个示例,因此这里有一个:

      public IEnumerable<YourType> RetrieveData(string tableName, string name)
              {
                  string sql = string.Format("Select * FROM {0} where Name = '{1}'", tableName, name);
      
                  var result = YourDataContext.ExecuteQuery(typeof(YourType), sql);
      
                  return result;
              }
      

      注意YourType,因为您必须定义一个具有构造函数的类型(它不能是抽象或接口)。我建议您创建一个与您的 SQL 表具有完全相同属性的自定义类型。如果您这样做,ExecuteQuery 方法将自动将表中的值“注入”到您的自定义类型。像这样:

      //This is a hypothetical table mapped from LINQ DBML
      
      [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ClientData")]
          public partial class ClientData : INotifyPropertyChanging, INotifyPropertyChanged
          {
      private int _ID;
      
              private string _NAME;
      
              private string _AGE;
      }
      
      //This would be your custom type that emulates your ClientData table
      
      public class ClientDataCustomType 
          {
      
              private int _ID;
      
              private string _NAME;
      
              private string _AGE;
      }
      

      因此,在前一个示例中,ExecuteQuery 方法将是:

      var result = YourDataContext.ExecuteQuery(typeof(ClientDataCustomType), sql);
      

      【讨论】:

        猜你喜欢
        • 2011-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多