gpt4 book ai didi

c# - LINQ 查询无法评估 StartsWith 中的 GET 参数

转载 作者:行者123 更新时间:2023-11-30 17:44:43 25 4
gpt4 key购买 nike

我正在尝试使用 .NET Web API 和使用 LINQ 和 MySQL 数据库的 Entity Framework 通过 GET 请求(在 Angular.js 中)进行查询。

http://localhost/ProductsApp/api/clientes/GetByName/M

问题是 GET 传递的参数没有被评估,我没有得到任何结果(即使 name 被正确设置为 "M"给调试器)。但是,如果我硬编码一个字符串,我会得到预期的结果。

    [ActionName("GetByName")]
public IEnumerable<cliente> GetByName(string name)
{

var query = from c in context.clientes where c.nome.StartsWith(name) select c;
var query2 = from c in context.clientes where c.nome.StartsWith("M") select c;
var query3 = context.clientes.Where(c => c.nome.StartsWith(name));
var query4 = context.clientes.Where(c => c.nome.StartsWith("M"));

return query.ToList();
}

我的 WebApiConfig.cs 有以下几行:

config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null
);

我假设 LINQ 在执行时会解析变量,如下所示(我删除了查询中不重要的部分):

query.ToString()
"SELECT [...] WHERE `Extent1`.`nome` LIKE 'p__linq__0%'"
query2.ToString()
"SELECT [...] WHERE `Extent1`.`nome` LIKE 'M%'"
query3.ToString()
"SELECT [...] WHERE `Extent1`.`nome` LIKE 'p__linq__0%'"
query4.ToString()
"SELECT [...] WHERE `Extent1`.`nome` LIKE 'M%'"

query2query4 都返回正确的值,而queryquery3 没有。为什么?我怎样才能让它发挥作用?

最佳答案

这是 MySQL Entity Framework 6.9.5 报告的错误

错误 #74918:Entity Framework 6 的查询结果不正确: https://bugs.mysql.com/bug.php?id=74918

它已在 MySQL Connector/Net 6.7.7/6.8.5/6.9.6 版本中修复。

变更日志:使用 Entity Framework 6,传递对“StartWith”的字符串引用子句会返回不正确的结果。

或者,一种解决方法是使用 .Substring(0) 强制实体不使用 LIKE(可能会影响性能)。

var query = context.clientes.Where(c => c.nome.StartsWith(name.Substring(0)));

关于c# - LINQ 查询无法评估 StartsWith 中的 GET 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29132130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com