使用 .Contains 方法进行 Linq-To-SQL 文本搜索
我有一个表,我需要在其中对文本字段进行不区分大小写的搜索。
如果我直接在数据库上的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论