【发布时间】:2015-04-09 05:38:47
【问题描述】:
我正在尝试更新 2 条记录:
- 用户记录(布尔型和自定义对象)
- 自定义对象(名为 MoviesDB)
我正在像这样使用 UserManager:
private UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
代码是:
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);
}
正如你在我的 cmets 中看到的,最后一行代码:
UserManager.Update(user);
正在按预期更新用户记录,但也在数据库中创建我不想要的新电影记录。
我只想更新现有的电影记录和现有的用户记录。
【问题讨论】:
-
将 db.savechanges() 放在 usermanager.Update(user) 之后
-
这样做不会改变行为,它仍然会创建一个新的电影记录,但现在我也遇到了一个异常:
The property 'ID' is part of the object's key information and cannot be modified.
标签: c# asp.net-mvc entity-framework asp.net-mvc-5