0

I want to get user ID from client context by looping through groups. I wrote following code. When I run this code I get an exception

"The property or field 'Id' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."

using (ClientContext ctx = new ClientContext(siteURL))
            {
                //Use the following line if you wish to connect to sharepoint site using
                //a different credential than what the application is running under.
                //ctx.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                ctx.Credentials = cred;

                Web wsite = ctx.Web;
                ctx.Load(wsite, w => w.HasUniqueRoleAssignments, w => w.RoleAssignments.Include(roleAssigned => roleAssigned.Member.Title,
                        roleAssigned => roleAssigned.RoleDefinitionBindings.Include(
                        roleDef => roleDef.Name)));
                ctx.ExecuteQuery();
                ctx.Load(ctx.Web, web => web.Title);
                ctx.ExecuteQuery();

                WebCollection websiteCollections = ctx.Web.Webs;
                ctx.Load(wsite);
                ctx.Load(websiteCollections);
                ctx.ExecuteQuery();
                RoleAssignmentCollection rac = wsite.RoleAssignments;
                if (rac != null && rac.Count != 0)
                {
                    foreach (RoleAssignment ra in rac)
                    {
                        //Get only groups and skip users directly added to site
                        if (ra.Member.ToString() != "Microsoft.SharePoint.Client.User")
                        {
                            foreach (RoleDefinition rd in ra.RoleDefinitionBindings)
                            {
                                //Skip groups which has Contribute or Read permission
                                if (!(rd.Name == "Contribute" || rd.Name == "Read"))
                                {
                                   int id=ra.Member.Id;
                                }
                            }
                        }
                }
            }
1

You should load the ra.Member object once before accessing its properties.

Your code should look something like this inside the last if block.

    if (!(rd.Name == "Contribute" || rd.Name == "Read"))
    {
       ctx.Load(ra.Member); 
       ctx.ExecuteQuery();  
       int id = ra.Member.Id;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.