2014-09-28 41 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

相關問題