日期:2014-05-20  浏览次数:20848 次

来问个怪问题。。。。。。。。。。。。。。。。。加分了,都来看看。。。。。。。。。.
数据库有4张表,其中大家都有的字段有20个,然后只有几个字段是每表特有的
别骂表设计太烂,哈哈,现不考虑改表结构。

4表都拉到DataContext里,现在url参数接收到的表名是string的,
每次查询、修改都要switch + 4个case,

怎么办??

代码比如:
swicth(type)
{
  case "table1": grid.DataSource = datacontext.table1.Take(5); break;
  case "table2": grid.DataSource = datacontext.table2.Take(5); break;
  case "table3": grid.DataSource = datacontext.table3.Take(5); break;
  case "table4": grid.DataSource = datacontext.table4.Take(5); break;
}

------解决方案--------------------
var metaTable = db.Mapping.GetTables().Where(o => o.TableName == "Customers").SingleOrDefault();
Debug.Assert(metaTable != null);
var table = db.GetTable(metaTable.RowType.Type);

顺便打个广告,ALinq -- 支持多种数据库的Linq to DB,绝对好用,官网:http://www.alinq.org
------解决方案--------------------
你可以加个类型转换的吧。例如(Table<Customer>)table
------解决方案--------------------
手写DATACONTEXT类 或者自己写个 静态方法 封装

class xxx{

pubic static xxx get(type){

swicth(type)
{
case "table1": return datacontext.table1.Take(5);
case "table2": return datacontext.table2.Take(5); 
...

}

}

}
------解决方案--------------------
up
------解决方案--------------------
C# code
private IEnumerable GetDataSource(string tableName)
        {
            DataClasses1DataContext db = new DataClasses1DataContext();
            var metaTable = db.Mapping.GetTables().Where(o => o.TableName == tableName).SingleOrDefault();

            var table = db.GetTable(metaTable.RowType.Type);

            IEnumerable query = db.ExecuteQuery(table.ElementType, "select top 5 * from " + tableName);

            return query;
        }

------解决方案--------------------
探讨
引用:
手写DATACONTEXT类 或者自己写个 静态方法 封装

class xxx{

pubic static xxx get(type){

swicth(type)
{
  case "table1": return datacontext.table1.Take(5);
  case "table2": return datacontext.table2.Take(5);
  ...

}

}

}


这里4个return的类型都是不一样的,xxx不是固定,怎么实现?