【问题标题】:c# linq query generates "ESCAPE '~'" syntax when translating "StartsWith" to sql "LIKE"c# linq 查询在将 "StartsWith" 转换为 sql "LIKE" 时生成 "ESCAPE '~'" 语法
【发布时间】:2011-03-25 00:27:19
【问题描述】:

奥拉。我在下面有这个 linq 语法,它在下面生成 sql。接收查询的 sql server 数据库拒绝 linq 附加的“ESCAPE '~'”。我仍在研究,但欢迎任何观点!

var rc = (
    from x in dc.Candidate
    join xs in dc.CandidateStatus on x.StatusId equals xs.CandidateStatusId
    join xss in dc.CandidateStatus on xs.SystemStatusId equals xss.CandidateStatusId
    where
        _active.Contains(xss.Code)
        && (x.NickName.StartsWith(startsWith) || x.FirstName.StartsWith(startsWith))
    orderby x.NickName, x.FirstName, x.LastName
    select new ListItem {
        Id = x.CandidateId,
        Label = FormatIndividual(x.LastName,x.FirstName,x.NickName)
    });
return rc.ToList<ListItem>();

SELECT [t0].[candid] AS [Id], [t0].[lastnm] AS [lastName], [t0].[firstnm] AS [firstName], [t0].[nicknm] AS [nickName]
FROM [ats].[cand] AS [t0]
INNER JOIN [ats].[candstatus] AS [t1] ON [t0].[statusid] = ([t1].[candstatusid])
INNER JOIN [ats].[candstatus] AS [t2] ON [t1].[sysstatid] = ([t2].[candstatusid])
WHERE ([t2].[code] IN (@p0, @p1, @p2)) AND (([t0].[nicknm] LIKE @p3 ESCAPE '~') OR ([t0].[firstnm] LIKE @p4 ESCAPE '~'))
ORDER BY [t0].[nicknm], [t0].[firstnm], [t0].[lastnm]

在下面实现。不再需要 sql server 通配符('%' - 即被转义的内容)。

        ...
        //&& (x.NickName.StartsWith(startsWith) || x.FirstName.StartsWith(startsWith))
        && (x.NickName.Substring(0,1).Equals(startsWith) || x.FirstName.Substring(0,1).Equals(startsWith))
        ...

【问题讨论】:

    标签: c# sql-server linq escaping


    【解决方案1】:

    http://msdn.microsoft.com/en-us/library/ms179859.aspx - 参见:C. 使用 ESCAPE 子句

    ~ 字符被用作@p3 中值的转义字符。

    【讨论】:

    • 我是这么想的,但没必要。有没有办法在它到达 sql server 之前将其切除?
    • 如果startsWith中的值包含不需要转义的字符,则添加它,例如%。你为startsWith 传递了什么值?
    • 这是另一个问题:stackoverflow.com/questions/1879429/…
    • 啊,我的杜哈。我确实使用'%',因为它是“以”开头的。哦,知识渊博的人,我在哪里以及如何补救?该查询不返回任何数据,但如果我删除“ESCAPE”并直接针对数据库运行它,它会返回很多。我见过的其他例子,我不知道我可以在哪里应用“@”之类的......
    • 啊!你很快! (这个网站很棒......)我现在会阅读/应用链接。谢谢!
    猜你喜欢
    • 2021-08-04
    • 2019-10-23
    • 2017-11-05
    • 2013-05-25
    • 1970-01-01
    • 2017-11-25
    • 2020-12-13
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多