UserManager更新用户记录,但同时也创建新记录 [英] UserManager updating a user record but creating a new record as well

查看:96
本文介绍了UserManager更新用户记录,但同时也创建新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to update 2 records:

  1. 用户记录(布尔型和自定义对象)
  2. 自定义对象(名为MoviesDB)

我正在像这样使用UserManager:

I'm using UserManager like so:

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

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

as you can see in my comments, the last line of code:

UserManager.Update(user);

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

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.

推荐答案

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

The problem is that you are using two database contexts: One for the UserManager and the other for the data.

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

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

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

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)

这篇关于UserManager更新用户记录,但同时也创建新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆