Linq to SQL中的动态表名

3

大家好,我有一个非常糟糕的数据库需要处理,我选择使用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();
}

我想用可枚举的记录填充我的ViewData。
2个回答

3
您可以在DataContext实例上调用ExecuteQuery方法。您需要调用接受Type实例的重载版本,如下所述:

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

假设您有一个已正确标记为表的类型,将该类型的 Type 实例传递给 SQL 将会得到您想要的结果。

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表具有完全相同属性的自定义类型。如果您这样做,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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接