LINQ到实体,使用SQL LIKE操作 [英] LINQ to Entity, using a SQL LIKE operator

查看:99
本文介绍了LINQ到实体,使用SQL LIKE操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个LINQ到从表中提取实体查询,但我需要能够创造一个模糊类型的搜索。所以,我需要添加一个where子句,通过姓氏,如果他们添加的标准在搜索框中搜索(文本框,可以是空白---在这种情况下,它拉的所有内容)。

I have a LINQ to ENTITY query that pulls from a table, but I need to be able to create a "fuzzy" type search. So I need to add a where clause that searches by lastname IF they add the criteria in the search box (Textbox, CAN be blank --- in which case it pulls EVERYTHING).

下面是我到目前为止有:

Here is what I have so far:

    var query = from mem in context.Member
                orderby mem.LastName, mem.FirstName
                select new
                {
                    FirstName = mem.FirstName,
                    LastName = mem.LastName,

                };

这会拉出来的一切成员表,它是在实体对象的。

That will pull everything out of the Member table that is in the Entity object.

然后我有一个除了逻辑:

Then I have an addition to the logic:

sLastName = formCollection["FuzzyLastName"].ToString();

if (!String.IsNullOrEmpty(sLastName))
   query = query.Where(ln => ln.LastName.Contains(sLastName));

问题是,当搜索按钮pssed $ P $,不返回任何结果(0结果)。我已经对运行SQL Server的,我希望在这里发生的查询,并将其返回6结果。

The problem is when the search button is pressed, nothing is returned (0 results). I have run the query against the SQL Server that I expect to happen here and it returns 6 results.

这是我想到的查询:

SELECT mem.LastName, mem.FirstName FROM Members mem WHERE mem.LastName LIKE '%xxx%'

(当XXX被输入到文本框)

(when xxx is entered into the textbox)

任何人看到什么不对的?

Anyone see anything wrong with this?

编辑:修正了SELECT查询。我的意思是它读LIKE'%XXX%(NOT ='XXX)

Fixed the SELECT query. I meant for it to read LIKE '%xxx%' (NOT = 'xxx")

推荐答案

我想你想使用包含这样的字符串参数()功能:

var query = from mem in context.Member
    where mem.LastName.Contains("xxx")
    orderby mem.LastName, mem.FirstName
    select new
    {
        FirstName = mem.FirstName,
        LastName = mem.LastName,
    };

我想你也可以使用 StartsWith()的endsWith()这将是等效于SQL XXX%'和'%XXX分别。

I think you can also use StartsWith() and EndsWith() which would be equivalent to the SQL 'xxx%' and '%xxx" respectively.

这篇关于LINQ到实体,使用SQL LIKE操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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