User.Groups 尝试在 SharePoint CSOM C# 中枚举时为空

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

我想通过 CSOM C# 在 SharePoint 2013 中通过用户 ID 获取用户:

        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)
                {
                    ...
                }

但我总是收到以下错误消息:

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.

我想做的是:

我从今天早上开始就在谷歌上搜索,但找不到任何solution/description如何解决这个问题。

这类似于 EF 急切与延迟加载问题。在 SP 中,默认只加载对象的简单属性(字符串、日期、数字、布尔值)。其他属性将需要显式加载。为此,您需要这样做:

clientContext.Load(gUser.Groups);

这也将加载 Groups 集合。现在您可以访问它了。