最近在用LINQ to Entities,看看下面的代码
//获取分页数据
var admins = from aa in db.VAccountAdmins
select aa;
//处理过滤规则
if (null != filterRules)
{
JArray roles = (JArray) JsonConvert.DeserializeObject(filterRules);
foreach (var fr in roles)
{
string field = fr["field"].ToString();
string op = fr["op"].ToString();
string value = fr["value"].ToString();
switch (field)
{
case "account_id":
switch (op)
{
case "all":
break;
case "equal":
admins = admins.Where(a => a.account_id == int.Parse(value));
break;
}
break;
}
}
//处理排序
PagedList<VAccountAdmin> alist = null;
if (order == "desc")
{
alist = admins.OrderByDescending(a => sort).ToPagedList(page, rows);
}
else
{
alist = admins.OrderBy(a => sort).ToPagedList(page, rows);
}
//返回easy json数据
var gridData = new
{
total = db.VAccountAdmins.ToList().Count,
rows = alist
};
return Json(gridData);
乍一看没问题,可是运行却抛出异常:
LINQ在筛选条件中如果使用率lanbla表达式,则不能在使用ToString、Int.Palse等C#代码。深层次的原因在于lambula表达式的解析。
把C#代码单独写出来,然后LINQ里面仅仅传送变量。
switch (field)
{
case "account_id":
switch (op)
{
case "all":
break;
case "equal":
int aid = int.Parse(value);
admins = admins.Where(a => a.account_id ==aid );
break;
}
break;
}