2014-09-28 69 views
0

AccountController已通过Visual Studio模板创建。我想记录使用者所做的一些动作,其中一人被登录的ApplicationUserAction保存有关行动信息采取:向AccountController中的数据库添加新对象时IEntityChangeTracker的多个实例无法引用实体对象

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

出了什么问题,我没有任何问题添加到数据库呢。

回答

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(); 
+0

请问您在答案中详细说明了为什么会出现这种问题? – Yoda 2014-09-28 19:05:25

+0

当您从上下文加载实体时,上下文会跟踪它。该框架不会允许实体被多个上下文跟踪。因此,在该实体可以被另一个上下文使用之前,您需要通过context.Detach方法或通过从新上下文中加载它来复制它,就像这个例子一样 – ESG 2014-09-29 01:08:57

相关问题