UserManager updating a user record but creating a new record as well

廉价感情. 提交于 2019-12-02 08:03:01

The problem is that you are using two database contexts: One for the UserManager and the other for the data.

If you want to manipulate the user field, this has to be done in the same database context:

using (ApplicationDbContext dbCtx = new ApplicationDbContext())
{
    // use the same context for the UserManager
    UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(dbCtx));
    // user to update
    var user = UserManager.Users
        .ToList()
        .First(u => u.Id == User.Identity.GetUserId());

    // movie to update
    var movie = dbCtx.Movies.SingleOrDefault(m => m.Name == "Star Wars");

    // this is the  only property i want to update
    movie.IsRented = true;

    dbCtx.SaveChanges();

    // user update
    user.IsRenting = true;
    user.MovieRented = movie;

    // this is should do the trick
    UserManager.Update(user);
}

As you used a separate database connection, EF thinks that the movie object is new (if does not belong to the user manager's db context)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!