linq中有一种方法可以使用字符串来调用表吗?我尝试了linq动态,但没有找到我想要的东西。所以基本上我会有一个字符串,我在参数中传递,我将用它来调用我的表:
前:
public IEnumerable<Category> SearchInTable(string table)
var context = new MapEntities() ;
myTable = context.Tables[table]; // something like that. Table == Country
return myTable.Where(x => x.name.Contains("Canada")).OrderByDescending(o => o.id).Take(10);
我希望我很清楚!谢谢
答案 0 :(得分:0)
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();
(我可能也不会把.Take(10)放在搜索中,我会想出一个更好的名字,比如ContainsCanada,或者让搜索更通用一些)