本人不善于言辞,直接开门见山
环境:EF6.0.0.0+MySQL Server5.6+MySqlConnector6.9.5.0
问题点如下:
1 var username = "admin"; 2 var lst = userService.GetQuery().Where(p => p.UserName.Contains(username)); 3 foreach (var user in lst) 4 { 5 Console.WriteLine(user.Id); 6 7 Console.WriteLine(user.UserName); 8 }
1、GetQuery是封装的,返回IQueryable<T>类型,采用以上查询方式,输出SQL语句为:
SELECT `Extent1`.`Id`, `Extent1`.`CaeateBy`, `Extent1`.`CreateDate`, `Extent1`.`CreateIp`, `Extent1`.`DefualtLang`, `Extent1`.`Descripton`, `Extent1`.`IsSystem`, `Extent1`.`LastEditBy`, `Extent1`.`LastEditDate`, `Extent1`.`LastEditIp`, `Extent1`.`Password`, `Extent1`.`RealName`, `Extent1`.`StatusId`, `Extent1`.`TypeId`, `Extent1`.`UserName` FROM `User` AS `Extent1` WHERE `Extent1`.`UserName` LIKE '%p__linq__0%'
为毛是 %p__linq__0% ??
如果用以下查询方式:
var lst = userService.GetQuery().Where(p => p.UserName.Contains("admin"));
输入SQL便是正确的:
SELECT `Extent1`.`Id`, `Extent1`.`CaeateBy`, `Extent1`.`CreateDate`, `Extent1`.`CreateIp`, `Extent1`.`DefualtLang`, `Extent1`.`Descripton`, `Extent1`.`IsSystem`, `Extent1`.`LastEditBy`, `Extent1`.`LastEditDate`, `Extent1`.`LastEditIp`, `Extent1`.`Password`, `Extent1`.`RealName`, `Extent1`.`StatusId`, `Extent1`.`TypeId`, `Extent1`.`UserName` FROM `User` AS `Extent1` WHERE `Extent1`.`UserName` LIKE '%admin%'
太奇葩了!!
结果搞了一整天,无意中发现如下解决方法如下:
1 var username = "admin"; 2 var lst = userService.GetQuery().Where(p => p.UserName.Contains(username.Trim())); //或ToLower() 3 foreach (var user in lst) 4 { 5 Console.WriteLine(user.Id); 6 7 Console.WriteLine(user.UserName); 8 }
就会生成如下正确的SQL:
Query SELECT `Extent1`.`Id`, `Extent1`.`CaeateBy`, `Extent1`.`CreateDate`, `Extent1`.`CreateIp`, `Extent1`.`DefualtLang`, `Extent1`.`Descripton`, `Extent1`.`IsSystem`, `Extent1`.`LastEditBy`, `Extent1`.`LastEditDate`, `Extent1`.`LastEditIp`, `Extent1`.`Password`, `Extent1`.`RealName`, `Extent1`.`StatusId`, `Extent1`.`TypeId`, `Extent1`.`UserName` FROM `User` AS `Extent1` WHERE (LOCATE(TRIM('admin'), `Extent1`.`UserName`)) > 0
虽然没有翻译成Like查询,但是却翻译成了Locate查询!! 真是奇葩,求高手解释
但是Locate查询效率要高于like查询!!
如下:
===========================================
虽然问题是暂时解决了,但是原因不明!请各位大虾指教!