项目需求,因为项目中存在很多表,这些表的内容需要呈现给客户浏览.转载请注明出处
相信很多写过程序的设计者很容易的用以下方式实现
在SqlConnect ,DataSet 的方式,我们很轻松的可以通过Sql的字符变化来实现单表动态查询
string sTableName="Dep"; string connectionstr="连接字符串"; Sql ="select * from "+sTableName; SqlConnection conn=new SqlConnection(); conn.ConnectionString = _ConnectionString; conn.open(); SqlDataAdapter adapter=new SqlDataAdapter(sql,conn); DataSet ds=new DataSet(); adapter.Fill(ds); //绑定数据 this.GridControl.DataSource=ds.Tables[]; ....
以上都是书本上很经典的范例,我就不详细列出
在开发Linq项目过程中,需要对一个表的数据进行查询,通常Linq的语法一般是这样:
DataClass1DataContext context=new DataClass1DataContext(); System .Data.Linq.Table<Dep> dt=context.GetTable<dep>();//重复写这句 //绑定数据 this.GridControl.DataSource=dt;
按照上面的做法.每次使用不用的表,我们必须重复的写以上的代码,从软件设计的角度出发,这些很多时候是无用的操作.
经过不断地测试,通过反射的方法可以实现动态表查询
如果表名发生变化,则我们不能直接实现<TableName>来实现
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void simpleButton1_Click(object sender, EventArgs e)
{
getLinqCommonTable("DepartmentShip"); getLinqCommonTable("DepartmentShip"," OID=2");
} /// <summary>
/// 通过动态字符串获取单表数据
/// </summary>
private void getLinqCommonTable(string sTableName)
{
ArrayList list = new ArrayList();
DataClasses1DataContext Context = new DataClasses1DataContext();
string sNamespace = new DataClasses1DataContext().GetType().Namespace;
Type t = Type.GetType(String.Format("{0}.{1}", sNamespace, sTableName), true, true);
var temp = Activator.CreateInstance(t); var q = Context.ExecuteQuery(typeof(DepartmentShip), "select * from DepartmentShip");
foreach (object c in q)
{
list.Add(c);
Console.WriteLine(c);
}
gridControl1.DataSource = list;
gridControl1.Refresh();
}
/// <summary>
/// 通过动态字符串获取单表数据
/// </summary>
private void getLinqCommonTable(string sTableName,string condition)
{
ArrayList list = new ArrayList();
DataClasses1DataContext Context = new DataClasses1DataContext();
string sNamespace = new DataClasses1DataContext().GetType().Namespace;
Type t = Type.GetType(String.Format("{0}.{1}", sNamespace, sTableName), true, true);
var temp = Activator.CreateInstance(t);
var q = Context.ExecuteQuery(temp.GetType(), "select * from DepartmentShip where "+condition);
foreach (object c in q)
{
list.Add(c);
Console.WriteLine(c);
}
gridControl1.DataSource = list;
gridControl1.Refresh();
} }
通过上述代码我们可以实现LINQ单表通过查询方法