c#linq查询在将“StartsWith”翻译为sql“LIKE”时生成“ESCAPE'〜'”语法

时间:2011-03-25 00:27:19

标签: c# sql-server linq escaping

ORA。我在下面有这个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))
        ...

1 个答案:

答案 0 :(得分:0)

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

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