Linq to Entities:在 NText 字段上使用 ToLower() [英] Linq to Entities : using ToLower() on NText fields

查看:19
本文介绍了Linq to Entities:在 NText 字段上使用 ToLower()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 SQL Server 2005,带有区分大小写的数据库..

I'm using SQL Server 2005, with a case sensitive database..

在搜索功能中,我需要创建一个带有where"子句的 Linq To Entities (L2E) 查询,该查询将多个字符串与数据库中的数据与这些规则进行比较:

In a search function, I need to create a Linq To Entities (L2E) query with a "where" clause that compare several strings with the data in the database with these rules :

  1. 比较是包含"模式,而不是严格比较:很容易,因为 L2E 中允许字符串的 Contains() 方法
  2. 比较必须不区分大小写:我在两个元素上使用 ToLower() 来执行不区分大小写的比较.

所有这些都表现得非常好,但我遇到了以下异常:参数数据类型 ntext 对于下层函数的参数 1 无效"在我的字段之一上.

All of this performs really well but I ran into the following Exception : "Argument data type ntext is invalid for argument 1 of lower function" on one of my fields.

该字段似乎是 NText 字段,我无法对其执行 ToLower().
我该怎么做才能在该 NText 字段上执行不区分大小写的 Contains() ?

It seems that the field is a NText field and I can't perform a ToLower() on that.
What could I do to be able to perform a case insensitive Contains() on that NText field ?

推荐答案

切勿使用 .ToLower() 执行不区分大小写的比较.原因如下:

Never use .ToLower() to perform a case-insensitive comparison. Here's why:

  1. 这可能是错误的(您的客户端排序规则可能是土耳其语,而您的数据库排序规则不是).
  2. 非常效率低下;发出的 SQL 是 LOWER 而不是 = 并带有不区分大小写的排序规则.
  1. It's possibly wrong (your client collation could be, say, Turkish, and your DB collation not).
  2. It's highly inefficient; the SQL Emitted is LOWER instead of = with a case-insensitive collation.

改为使用 StringComparison.OrdinalIgnoreCaseStringComparison.CurrentCultureIgnoreCase:

var q = from f in Context.Foos
        where f.Bar.Equals("hi", StringComparison.OrdinalIgnoreCase)
        select f;

但是对于 Contains() 有一个问题:与 EqualsStartsWith 等不同,它没有重载 aStringComparison 参数.为什么?好问题;问微软.

But for Contains() there's a problem: Unlike Equals, StartsWith, etc., it doesn't have an overload for a StringComparison argument. Why? Good question; ask Microsoft.

那,结合 SQL Server 对 LOWER 的限制意味着没有简单的方法可以做你想做的事.

That, combined with SQL Server's limitation on LOWER means there's no simple way to do what you want.

可能的解决方法可能包括:

Possible workarounds might include:

  • 使用全文索引,并在程序中进行搜索.
  • 如果可能,请使用 EqualsStartsWith 代替
  • 更改列的默认排序规则?

这篇关于Linq to Entities:在 NText 字段上使用 ToLower()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆