SharePoint 2016 Logo

There are a lot of cases when you need to get the items by the author. For me the only correct way to get the SharePoint list items by user with CAML is like this:

<Where><Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='Integer'>123</Value></Eq></Where>

In C# if you use something like “SPUser user = web.Users.GetByEmail(email)” or another method GetById can make an exception if user does not exist.

I used the method ‘EnsureUser’ and it looked like this:

SPUser user = web.EnsureUser(fullLoginName);

Obviously, to achieve SPUserId I’ve got SPUser object and got the property user.ID. This value I set into CAML Query. But it return Null records!! WT??

I made a lot of tests with CAML Query – wrapped it with ‘Query’ and removed it, changed the syntax of the string formatting, but everything was useless.

I also executed similar scripts in Powershell. It also returned the same userID as a result of user information and null from the list.

Then I decided to check the SiteUsers in PowerShell

$web = Get-SPWeb "http://test-myweb.com/"
$users = $web.SiteUsers  | Where { $_.UserLogin -like '*myuser*' } | select UserLogin, ID, DisplayName

It’s good that I know how to make the queries like this without AI. The result was like this:

UserLogin                     ID DisplayName
--------- -- -----------
MYDOMAIN\myuser 11 myuser
i:0#.w|mydomain\myuser 22 myuser

As you can see, there are 2 different objects. And the AuthorId is what inside ‘i:0#.w|mydomain\myuser’

I updated a bit my method and did this way:

SPUser user = web.EnsureUser("i:0#.w|"  + fullLoginName);
fullLoginName – var with format 'mydomain\myuser'

That’s all, it works.

The problem was that in my development environment I could not implement the same situation. I had to add a lot of logging to determine.