public IQueryable<Category> SearchInTable(string table)
{
var context = new MapEntities();
IQueryable<Category> myTable;
switch(table)
{
case "Canada": myTable=context.Canada; break;
case "UnitedStates": myTable=context.UnitedStates; break;
else throw new Exception("Table not found");
}
return myTable.Where(x => x.name.Contains("Canada")).OrderByDescending(o => o.id).Take(10);
}
雖然你應該打破這種分離:
public static IQueryable<Category> GetTable(this DataContext context,string table)
{
IQueryable<Category> myTable;
switch(table)
{
case "Canada": myTable=context.Canada; break;
case "UnitedStates": myTable=context.UnitedStates; break;
else throw new Exception("Table not found");
}
return myTable;
}
public static IQueryable<Category> Search(this IQueryable<Category> context)
{
return context.Where(x => x.name.Contains("Canada")).OrderByDescending(o => o.id).Take(10);
}
,那麼你可以這樣做:
var result=new MapEntities().GetTable("Canada").Search();
(我可能不會放。取(10)在搜索中,我會想出一個更好的名稱,比如ContainsCanada,或者使搜索更具通用性)
什麼是數據訪問技術你在用嗎?實體框架? –
[從LINQ DataContext中的表名獲取表數據]可能的重複(http://stackoverflow.com/questions/1919632/get-table-data-from-table-name-in-linq-datacontext) –