簡體   English   中英

UserManager更新用戶記錄,但也創建新記錄

[英]UserManager updating a user record but creating a new record as well

我正在嘗試更新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);
}

如您在我的評論中看到的,最后一行代碼:

UserManager.Update(user);

正在按預期方式更新用戶記錄,但還在數據庫中創建了我不想要的Movie的新記錄。

我想要的只是更新現有的電影記錄和現有的用戶記錄。

問題在於您正在使用兩個數據庫上下文:一個用於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認為電影對象是新的(如果不屬於用戶管理器的數據庫上下文)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM