2009-02-12 115 views
3

大家好我有一个可怕的数据库我得和我一起工作,linq to sql是我从中检索数据的选项。任何正在尝试通过根据用户选择抛出不同表名来重用函数的方法,并且我无法知道如何修改DataContext查询中的TEntity或Table <>。Linq to SQL中的动态表名称

这是我现在的代码。

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。

回答

3

您可以调用DataContext实例上的ExecuteQuery方法。您将要调用了一个类实例的过载,这里概述:

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

假设你有一个正确归结为表型,传递一个类型实例为类型和SQL会给你你想要的。

+1

你介意提供了一个例子。 – Ayo 2009-02-17 21:25:27

0

由于casperOne已经回答,您可以使用ExecuteQuery方法首先重载(要求Type参数的那个)。因为我也有类似的问题,你问了一个例子,这里是一个:

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 Table完全相同的属性。如果这样做,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);