当WHERE子句具有特殊字符时,LINQ查询不返回结果

时间:2016-03-04 16:55:38

标签: c# linq

在我的脚本中,我正在动态构建一个字符串,然后将该字符串传递给WHERE语句的LINQ TO ENTITIES子句。当语句运行时,它无法找到任何结果,我无法弄清楚原因。如果我明确地将值硬编码到传递给语句的变量中,它可以正常工作,但如果我让系统为我构建它就会失败。为什么这会失败?

for (int i = 1; i <= TotalUsers; i++)
{
    var CurrentUser = db.Users.Where(u => u.ID == i).Select(u => u.ADUserName).First();
    UserPrincipalData = UserPrincipal.FindByIdentity(Context, CurrentUser);
    var UserDirectoryData = UserPrincipalData.GetUnderlyingObject() as DirectoryEntry;

    var Manager = (string)UserDirectoryData.Properties["manager"].Value;

    if (String.IsNullOrEmpty(Manager))
    {
        Manager = @"Company\Matthew.Verstraete";
    }
    else
    {
        var StartIndex = Manager.IndexOf("=") + 1;
        var EndIndex = Manager.IndexOf(",", StartIndex);
        var Length = EndIndex - StartIndex;
        Manager = Manager.Substring(StartIndex, Length);
        Manager = @"Company\" + Manager.Replace(" ", ".");
    }

    var ManagerID = db.Users.Where(u => u.ADUserName == Manager).Select(u => u.ID).FirstOrDefault();
    var UpdatedUser = db.Users.Find(i);
    UpdatedUser.ManagerID = ManagerID;
    db.SaveChanges();
}

如果IF语句为真并且变量被硬编码给我,则通过DeBug工作,然后从查询中正确设置ManagerID,如果失败并转到ELSE子句即使Manager变量也动态设置给我,它也会失败。

编辑: 代码不会在调试中引发任何错误。变量Manager总是以Company\\First.Last的形式获得正确的值(C#似乎正在逃避反斜杠)。所以当动态设置名称而不是静态设置名称时,我无法弄清楚为什么LINQ查询失败。我需要能够动态设置Manager名称并将其传递给查询,以便我可以将员工与管理员正确关联。

1 个答案:

答案 0 :(得分:0)

It would help to wrap your code in a try catch block and to give us the exception that was being thrown.

But my guess is that you might be getting an ArgumentOutOfRangeException

If this is the issue, then for your StartIndex or your EndIndex you might be getting -1, which means that the string searched for does not exist.

This would make your Length variable a negative number, and when using substring on a negative value would lead to the exception.

I would step through and see the values of your start and end index.

IndexOf: https://msdn.microsoft.com/en-us/library/7cct0x33(v=vs.110).aspx

Substring: https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx


Ok, I think I found the issue.

So you're using the @ sign in your else statement. However, you said that the value is Company\\First.Last. With the @ sign, the string gets considered as literal, so it's searching for "Company\\First.Last"

If you want to search for "Company\First.Last" you should remove the @ sign from the else statement.

I read this post to help me understand the issue: What's the @ in front of a string in C#?