Linq到SQL中的动态表名称 [英] Dynamic Table Names in Linq to SQL

查看:136
本文介绍了Linq到SQL中的动态表名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有我有一个可怕的数据库,我必须使用和linq到sql是从im取回数据的选项。任何我试图通过基于用户选择投入不同的表名称来重用一个函数,并且我没有办法修改DataContext Query中的TEntity或Table<>。



这是我现在的代码。

  public void GetRecordsByTableName(string table_name){

string sql =Select * from+ table_name;
var records = dataContext.ExecuteQuery< / *禁止的表名* />(sql);

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

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

解决方案

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



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



假设您有一个正确归属于该表的类型,传递该类型的Type实例,SQL将给您所需的。


Hi all I have a horrid database I gotta work with and linq to sql is the option im taking to retrieve data from. anywho im trying to reuse a function by throwing in a different table name based on a user selection and there is no way to my knowledge to modify the TEntity or Table<> in a DataContext Query.

This is my current code.

public void GetRecordsByTableName(string table_name){

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

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

I want to populate my ViewData with Enumerable records.

解决方案

You can call the ExecuteQuery method on the DataContext instance. You will want to call the overload that takes a Type instance, outlined here:

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

Assuming that you have a type that is attributed correctly for the table, passing that Type instance for that type and the SQL will give you what you want.

这篇关于Linq到SQL中的动态表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆