【问题标题】:UserManager updating a user record but creating a new record as wellUserManager 更新用户记录但也创建新记录
【发布时间】:2015-04-09 05:38:47
【问题描述】:

我正在尝试更新 2 条记录:

  1. 用户记录(布尔型和自定义对象)
  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


【解决方案1】:

问题在于您使用了两个数据库上下文:一个用于 UserManager,另一个用于数据。

如果你想操作user 字段,这必须在同一个数据库上下文中完成:

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);
}

由于您使用了单独的数据库连接,EF 认为电影对象是新的(如果不属于用户管理器的 db 上下文)

【讨论】:

  • 所以基本上你说的是我使用了“全局”UserManager,因此我得到了 2 个数据库上下文
  • 是的,这就是问题所在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 2023-01-12
  • 2016-05-19
相关资源
最近更新 更多