在AccountController中向数据库中添加新对象时,IEntityChangeTracker的多个实例无法引用实体对象

问题描述 投票:0回答:1

AccountController已通过Visual Studio通过模板创建。我要记录用户执行的某些操作,其中之一正在登录。ApplicationUserAction包含有关已执行操作的信息:

public class ApplicationUserAction {
    public int Id { get; set; }
    public String Description { get; set; }
    public DateTime TimeStamp { get; set; }
    public virtual ApplicationUser Actor { get; set; }
}

内部POST登录方法中,我向数据库添加了新操作,然后要保存它:

  protected WebApplication2.Models.ApplicationDbContext db { get; set; }

    public AccountController() {
        db = new ApplicationDbContext();
    }
...
...
...
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) {
    if (ModelState.IsValid) {
        var user = await UserManager.FindAsync(model.Email, model.Password);
        if (user != null) {
            await SignInAsync(user, model.RememberMe);
            //MY CODE
            Debug.WriteLine("HERE CODE");
            ApplicationUserAction action = new ApplicationUserAction { Description = "Logged in at " + DateTime.Now + " from IP " + Request.UserHostAddress + ".", TimeStamp = DateTime.Now, Actor = user };
            db.ApplicationUserActions.Add(action);
            db.SaveChanges();
            //END OF MY CODE
            return RedirectToLocal(returnUrl);
        } else {
            ModelState.AddModelError("", "Invalid username or password.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

但是当我登录到Web应用程序时,出现此异常:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.


Exception Details: System.InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

此行导致异常:db.ApplicationUserActions.Add(action);

出了什么问题,向数据库添加内容还没有任何问题。

asp.net-mvc entity-framework asp.net-mvc-5.1
1个回答
1
投票

从外观上看,在创建操作时,您引用的用户是通过另一个上下文进行跟踪的(UserManager中没有代码,因此很难分辨)。>>

您可能已将用户从先前的上下文中分离出来,或从当前上下文中查询了它的新实例。


编辑:

原始海报提供的内容:

这完成了工作。

ApplicationUser userSecondInstance = db.Users.Find(user.Id);
ApplicationUserAction action = new ApplicationUserAction { Description = "Logged in at " + DateTime.Now + " from IP " + Request.UserHostAddress + ".", TimeStamp = DateTime.Now, Actor = userSecondInstance };
db.ApplicationUserActions.Add(action);
db.SaveChanges();
© www.soinside.com 2019 - 2024. All rights reserved.