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

主宰稳场 提交于 2019-12-20 05:50:54

问题


I'm trying to update 2 records:

  1. a user record (bool and custom Object)
  2. a custom object (named MoviesDB)

I'm using UserManager like so:

private UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

and the code is:

using (ApplicationDbContext dbCtx = new ApplicationDbContext())
{
    // user to update
    var user = UserManager.Users
                .ToList()
                .First(u => u.Id == User.Identity.GetUserId());


    // movie to update
    var movie = db.MoviesDBs.SingleOrDefault(m => m.ID == id);

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

    db.SaveChanges();

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

    // this line creates a new movie record for some reason
    UserManager.Update(user);
}

as you can see in my comments, the last line of code:

UserManager.Update(user);

is updating the user record like expected but also creates a new record of Movie in the database which I don't want.

all I want is to update an existing movie record and existing user record.


回答1:


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)



来源:https://stackoverflow.com/questions/29511068/usermanager-updating-a-user-record-but-creating-a-new-record-as-well

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