In my script I am dynamically building a string and then passing the string into the WHERE
clause of a LINQ TO ENTITIES
statement. When the statement is run it fails to find any results and I can't figure out why. If I explicitly hard code a value into the variable that gets passed into the statement it works fine, but if I let the system build it for me it fails. Why is this failing?
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();
}
Working via DeBug if the IF
statement is true and the variable is hardcoded to me then the ManagerID
is set correctly from the query, if it fails and goes to the ELSE
clause it will fail even if the Manager
variable is dynamically set to me as well.
Edit:
The code does not throw any errors in debug. The variable Manager
always gets a the proper value in form of Company\\First.Last
(C# seems to be escaping the backslash). So I can't figure out why the LINQ query fails when the name is set dynamically but not statically. I need to be able to dynamically set the Manager name and pass it to the query so I can associate an employee to there manager correctly.