使用 .Contains 方法进行 Linq-To-SQL 文本搜索

发布于 2024-08-29 20:31:53 字数 1150 浏览 3 评论 0原文

我有一个表,我需要在其中对文本字段进行不区分大小写的搜索。

如果我直接在数据库上的 LinqPad 中运行此查询,它将按预期工作

Table.Where(tbl => tbl.Title.Contains("StringWithAnyCase"))
// also, adding in the same constraints I'm using in my repository works in LinqPad
// Table.Where(tbl => tbl.Title.Contains("StringWithAnyCase") && tbl.IsActive == true)

在我的应用程序中,我有一个公开 IQueryable 对象的存储库,该对象执行一些初始过滤,它看起来像这样

var dc = new MyDataContext();

public IQueryable<Table> GetAllTables()
{
    var ret = dc.Tables.Where(t => t.IsActive == true);
    return ret;
}

在控制器(它的 MVC 应用程序)中我使用这样的代码尝试模仿 LinqPad 查询:

var rpo = new RepositoryOfTable();
var tables = rpo.GetAllTables();
// for some reason, this does a CASE SENSITIVE search which is NOT what I want.
tables = tables.Where(tbl => tbl.Title.Contains("StringWithAnyCase");
return View(tables); 

该列在 SQL Server 2008 中被定义为 nvarchar(50)

**更新 **

我有一个部分类(对于我的一个来自 Linq-To-SQL 的实体)具有 IQueryable 属性,但不知何故从 EntitySet 返回 IQueryable 导致我以后的查询以 IEnumerable(读取 Linq-To-Objects)方式运行,即使它们作用于 IQueryable 类型。

I have a table, where I need to do a case insensitive search on a text field.

If I run this query in LinqPad directly on my database, it works as expected

Table.Where(tbl => tbl.Title.Contains("StringWithAnyCase"))
// also, adding in the same constraints I'm using in my repository works in LinqPad
// Table.Where(tbl => tbl.Title.Contains("StringWithAnyCase") && tbl.IsActive == true)

In my application, I've got a repository which exposes IQueryable objects which does some initial filtering and it looks like this

var dc = new MyDataContext();

public IQueryable<Table> GetAllTables()
{
    var ret = dc.Tables.Where(t => t.IsActive == true);
    return ret;
}

In the controller (its an MVC app) I use code like this in an attempt to mimic the LinqPad query:

var rpo = new RepositoryOfTable();
var tables = rpo.GetAllTables();
// for some reason, this does a CASE SENSITIVE search which is NOT what I want.
tables = tables.Where(tbl => tbl.Title.Contains("StringWithAnyCase");
return View(tables); 

The column is defined as an nvarchar(50) in SQL Server 2008.

** update **

I had a partial class (for one of my Entities from Linq-To-SQL) with an IQueryable property, but somehow returning an IQueryable from an EntitySet caused my later queries to behave in an IEnumerable (read Linq-To-Objects) way even though they were acting on IQueryable types.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文