0

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.

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
  • place the db.savechanges() after the usermanager.Update(user) – jonas vermeulen Apr 08 '15 at 09:42
  • doing this not changing the behavior, it's still creates a new movie record but now I get an exception as well: `The property 'ID' is part of the object's key information and cannot be modified.` – Sagiv b.g Apr 08 '15 at 09:51

1 Answers1

2

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)

Stephen Reindl
  • 5,659
  • 2
  • 34
  • 38