关于c#:UserManager更新用户记录,但也创建新记录

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

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

  • 用户记录(布尔和自定义对象)
  • 自定义对象(名为MoviesDB)
  • 我像这样使用UserManager:

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

    代码是:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    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);
    }

    如您在我的评论中看到的,最后一行代码:

    1
    UserManager.Update(user);

    正在按预期方式更新用户记录,但还会在数据库中创建我不想要的Movie的新记录。

    我想要的只是更新现有的电影记录和现有的用户记录。


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

    如果要操纵user字段,则必须在同一数据库上下文中完成:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    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认为电影对象是新的(如果不属于用户管理器的数据库上下文)