1

I am trying to access a user profile property in a list item event event receiver(item adding).

But I get the following error

The user could not be found in the database. You must first create this user by calling CreateUserProfile or GetUserProfile(true).

I have checked the user profile service for the user and the user has a profile in service, I also have checked the profile existence in code using userProfileManager.UserExists(accountName) and the profile exist but when I want to access it I get that error

Below is the code

SPServiceContext spServiceContext = SPServiceContext.GetContext(spSite);
UserProfileManager userProfileManager = new UserProfileManager(spServiceContext);

if (!userProfileManager.UserExists(accountName)) return string.Empty;

UserProfile userProfile = userProfileManager.GetUserProfile(false);
var retrunValue = userProfile[strKey].Value ?? string.Empty;

return retrunValue.ToString();
  • Can you please add the sample account name that you are using so that we can know the format. It has to be the login name of the user in the format domain\\userName – Priyaranjan KS Aug 6 '17 at 7:19
  • 1
    oh i see , let me check it , i think i should change userProfileManager.GetUserProfile(false) to userProfileManager.GetUserProfile(accountName); – Arash Aug 6 '17 at 7:47
2

I had to change

UserProfile userProfile = userProfileManager.GetUserProfile(false);

to

UserProfile userProfile = userProfileManager.GetUserProfile(accountName);

because sharepoint evener receiver doesn't run under the user who has caused the event.

it runs with another user, I don't know what user exactly, maybe spfarmadmin. so userProfileManager.GetUserProfile(accountName) will not return profile of a person who has created the item .

below is the complete code

SPServiceContext spServiceContext = SPServiceContext.GetContext(spSite);
UserProfileManager userProfileManager = new UserProfileManager(spServiceContext);

if (!userProfileManager.UserExists(accountName)) return string.Empty;

UserProfile userProfile = userProfileManager.GetUserProfile(accountName);
var retrunValue = userProfile[strKey].Value ?? string.Empty;

return retrunValue.ToString();
0

The login name of the user has to be in the format domain\userName.

Also see the below sample code :

if (upm.UserExists(loginUserName))
{
    UserProfile up = upm.GetUserProfile(loginUserName);
    //Remaining Logic
}

The loginUserName should be of the format domain\userName in the if block

User Profile Reference

enter image description here

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.