可以使用'stringcomparison'吗?
在数据库查询操作中,不可避免去考虑字母大小写的问题,比如要在movie表中查找“x-men”这部电影,为了不区分字母大小写,按照linq to memory的习惯,可能会写出如下代码:
dbcontext.dbset<movie>
.where(item => string.equals(item.title, "x-men", stringcomparison.invariantcultureignorecase)
但是上述代码执行会报错,提示 'stringcomparison'参数不支持。
invalidoperationexception: the linq expression 'dbset<movie>() .where(m => string.equals( a: m.genre, b: __moviegenre_0, comparisontype: invariantcultureignorecase))' could not be translated. additional information: translation of the 'string.equals' overload with a 'stringcomparison' parameter is not supported. see https://go.microsoft.com/fwlink/?linkid=2129535 for more information. either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'asenumerable', 'asasyncenumerable', 'tolist', or 'tolistasync'. see https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
怎么解决这个问题呢?如果你用的是sql server或mysql,那么很简单,去掉“stringcomparison.invariantcultureignorecase”这个参数就可以了,因为他们是默认大小写不敏感的。如果用的是大小写敏感的数据库,比如postgresql,就需要做一些特殊处理了,后面会讲到。
对于这类问题有一个暴力的解决方法,就是按报错提示的那样在查询客户端做筛选:
dbcontext.dbset<movie> .tolist() .where(item => string.equals(item.title, "x-men", stringcomparison.invariantcultureignorecase)
这样做的本质是返回所有的movie,然后在内存中做title匹配查询(linq to memory),而不是在db中做title的匹配查询,所以不会报 'stringcomparison'参数不支持的错误。这种方法在绝大多数场景下是不推荐的,因为 1. 性能差,查询是在内存中不是在db中,2. 占用内存,返回了整张表
为什么不能使用'stringcomparison'?
前面讲到有的数据库是默认大小写不敏感的:sql server,mysql;有的数据库是默认大小写敏感的:postgresql。那么数据库中大小写敏感与否是由什么控制的呢,排序规则(collation,一组规则,用于确定文本值的排序和相等性比较方式,可以在数据库,表和列上创建排序规则,排序规则是隐式继承的,比如在数据库上创建了排序规则,没有在表上创建排序规则,那么表会默认使用数据库的排序规则,列同理)。因为ef core不知道数据库,表,列支持/应用了什么样的排序规则,所以'stringcomparison'是没有意义的,ef core会将 string.equals 转化成数据库的相等( = )操作,由数据库根据列上应用的排序规则来决定是否区分大小写。
如何在查询中设置区分大小写与否?
既然区分大小写是由排序规则决定的,我们可以通过在查询中指定排序规则的方式来来设置是否区分大小写,例如sql server默认是不区分大小写的,我们可以通过 ef.functions.collate 来指定一个大小写敏感的排序规则"sql_latin1_general_cp1_cs_as"来达到精确匹配的目的
dbcontext.dbset<movie> .where(m => ef.functions.collate(item.title, "sql_latin1_general_cp1_cs_as") == "x-men")
但是这种显示指定排序规则的方法也不是非常推荐的,因为他会导致索引匹配失败,进而影响查询性能。索引隐式继承列上的排序规则,当显示指定的排序规则和创建索引时指定的排序规则(postgresql支持在创建索引时指定排序规则)或列的排序规则不一致时,会导致索引匹配失败,进而导致查询不能应用索引,这也是ef core没有将'stringcomparison'转换成排序规则的另一个原因。
因此一个相对完善的解决方案是,根据业务模型在列上指定合适的排序规则,而不是在代码中设置。如果数据库支持在列上创建多个索引,你也可以用显示指定排序规则的方式根据业务场景切换排序规则来匹配正确的索引。
参考文档:
https://learn.microsoft.com/en-us/ef/core/miscellaneous/collations-and-case-sensitivity
发表评论