Reputation: 413
Im trying to update an User and get nullreference. This is my code for updating user, i get the nullreference when i set the firstname in the else (when the object dont exist, then i tried to create it but it dont work)
the properties work fine, because my registration works and if the userprofile object exist on the user it's also fine
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
if (currentUser.UserProfileInfo != null)
{
currentUser.UserProfileInfo.FirstName = Firstname.Text;
currentUser.UserProfileInfo.LastName = Lastname.Text;
currentUser.UserProfileInfo.Adress = Adress.Text;
currentUser.UserProfileInfo.Zip = Zip.Text;
currentUser.UserProfileInfo.City = City.Text;
currentUser.UserProfileInfo.Mobile = Mobile.Text;
manager.UpdateAsync(currentUser);
}
else
{
UserProfileInfo UserProfileInfo = new UserProfileInfo();
currentUser.UserProfileInfo.FirstName = Firstname.Text;
currentUser.UserProfileInfo.LastName = Lastname.Text;
currentUser.UserProfileInfo.Adress = Adress.Text;
currentUser.UserProfileInfo.Zip = Zip.Text;
currentUser.UserProfileInfo.City = City.Text;
currentUser.UserProfileInfo.Mobile = Mobile.Text;
manager.UpdateAsync(currentUser);
}
Thanks
Upvotes: 0
Views: 273
Reputation: 650
Two possible scenarios come to my mind. It is difficult to say with this little information but here is my input:
You are not logged in while trying to use User.Identity.GetUserId(). This will return a null value for id and thus resulting in null currentUser. You are not checking if currentUser is null so that results in null reference exception when you are trying to access properties of null object.
You get the ApplicationUser object but the UserProfileInfo property is not created. There can be many reasons behind this depending on your implementation.
You should set your breakpoint on the follow row
currentUser.UserProfileInfo.FirstName = Firstname.Text;
And check if currentUser is null or UserProfileInfo is null.
Try this:
else
{
currentUser.UserProfileInfo = new UserProfileInfo();
currentUser.UserProfileInfo.FirstName = Firstname.Text;
currentUser.UserProfileInfo.LastName = Lastname.Text;
currentUser.UserProfileInfo.Adress = Adress.Text;
currentUser.UserProfileInfo.Zip = Zip.Text;
currentUser.UserProfileInfo.City = City.Text;
currentUser.UserProfileInfo.Mobile = Mobile.Text;
manager.UpdateAsync(currentUser);
}
Upvotes: 1