如何解决这个问题?
这是我的代码:
DateTime dtInicio = new DateTime(); DateTime dtFim = new DateTime(); Int32 codStatus = 0; if(!string.IsNullOrEmpty(collection["txtDtInicial"])) dtInicio = Convert.ToDateTime(collection["txtDtInicial"]); if(!string.IsNullOrEmpty(collection["txtDtFinal"])) dtFim = Convert.ToDateTime(collection["txtDtFinal"]); if (!string.IsNullOrEmpty(collection["StatusCliente"])) Convert.ToInt32(collection["StatusCliente"]); var listCLientResult = (from c in db.tbClientes orderby c.id where (c.effdt >= dtInicio || string.IsNullOrEmpty(collection["txtDtInicial"]) && (c.effdt <= dtFim || string.IsNullOrEmpty(collection["txtDtFinal"])) && (c.cod_status_viagem == codStatus || string.IsNullOrEmpty(collection["StatusCliente"]))) select c); return View(listCLientResult);
我得到的错误是:
LINQ to Entities不能识别方法’System.String get_Item(System.String)’,它不能转换为存储库的表达式.
解决方法
对数据库执行的Linq查询在被执行之前被转换为sql;但是收集[“txtDtInicial”]不能转换为sql,因为没有等效的sql语法,无论如何,数据库无法访问集合.您需要首先将collection [“txtDtInicial”]提取到变量中,并且在查询中仅使用此变量.
这是我会做的:
DateTime dtInicio = DateTime.MinValue; DateTime dtFim = DateTime.MaxValue; Int32 codStatus = 0; if(!string.IsNullOrEmpty(collection["txtDtInicial"])) dtInicio = Convert.ToDateTime(collection["txtDtInicial"]); if(!string.IsNullOrEmpty(collection["txtDtFinal"])) dtFim = Convert.ToDateTime(collection["txtDtFinal"]); if (!string.IsNullOrEmpty(collection["StatusCliente"])) codStatus = Convert.ToInt32(collection["StatusCliente"]); var listCLientResult = (from c in db.tbClientes orderby c.id where (c.effdt >= dtInicio) && (c.effdt <= dtFim) && (c.cod_status_viagem == codStatus) select c); return View(listCLientResult);
通过将dtInicio和dtFim初始化为MinValue和MaxValue,您不需要检查它们是否在查询中定义.