STORM
STORM

Reputation: 4341

User.Groups is empty when trying to enumerate in SharePoint CSOM C#

I want to get a user by its id in SharePoint 2013 via CSOM C#:

        clientContext ctx = new ClientContext(siteUrl);
        Web web = clientContext.Web;
        User gUser = web.GetUserById(selectedUserId);
        clientContext.Load(web);
        clientContext.Load(gUser);
        clientContext.ExecuteQuery();

                foreach (Group gGroup in gUser.Groups)
                {
                    ...
                }

But i get always the following error message:

The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

What i want to do is:

I am googling around since this morning, but cannot find any solution/description how to solve this.

Upvotes: 0

Views: 492

Answers (1)

CodingYoshi
CodingYoshi

Reputation: 27039

This is similar to EF eager vs lazy loading issue. In SP, only simple properties of objects are loaded by default (string, date, number, boolean). Other properties will need to be explicitly loaded. To do that, you need to do this:

clientContext.Load(gUser.Groups);

That will load the Groups collection as well. Now you can access it.

Upvotes: 1

Related Questions