LINQ to Entities不识别方法'System.String get_Item(System.String)'。

16

我该如何解决这个问题?

以下是我的代码:

    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)' 方法,无法将其转换为仓储表达式。


请看这个答案:https://dev59.com/Smw05IYBdhLWcg3waRGz问候 - MUG4N
是的,请查看推荐的问题,它回答了为什么您会收到错误,并且https://dev59.com/SW035IYBdhLWcg3wPNdk#5541505将告诉您如何构建一个有效的查询。 - Hari
3个回答

36

对于针对数据库执行的Linq查询,在执行之前会被转换为SQL;但是collection["txtDtInicial"]无法被翻译为SQL,因为没有等同的SQL语法,而且数据库也无法访问collection。你需要先将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);

通过将dtIniciodtFim初始化为MinValue和MaxValue,您无需检查它们是否在查询中定义。


4
为什么LINQ不比这更智能呢? - PeterX

11

Linq 查询最终会转换成 SQL 查询,而 LINQ 不知道如何处理 Session["UserName"](获取 "UserName" 项)。

一种常见的解决方法是使用一个本地变量来接收 Session["UserName"] 的值,并在 Linq 查询中使用它...

比如:

string loggedUserName = Session["LogedUsername"].ToString();
var userDetail = dc.faculties.Where(a => a.F_UserName.Equals(loggedUserName)).FirstOrDefault();

参考 http://mvc4asp.blogspot.in/


7

一句话概括:

在Linq(Entity)查询中不要使用字符串转换函数!

错误的写法:

user = db.Users.Where(u => u.Name == dt.Rows[i]["Name"].ToString()).FirstOrDefault();

正确:

string Name = dt.Rows[i]["Name"].ToString();
user = db.Users.Where(u => u.Name == Name).FirstOrDefault();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接