Reputation: 31024
I'm trying to update 2 records:
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.
Upvotes: 0
Views: 2796
Reputation: 5829
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)
Upvotes: 2