2013-02-14 39 views
0

對不起,我會盡我所能去做。SaveChanges()在拋出異常之前不起作用

我有實體「Usuario」從rbacManager接收對象,調用Login方法(見下文)。如您所見,此方法在無法與用戶密碼匹配時引發異常。在這種情況下,我必須增加屬性Intentos,以允許用戶只有三次失敗的機會。

問題如下:SaveChanges方法未保存在Usuario中修改的值。我認爲SaveChanges方法由於例外而失敗,但我不確定。我在網上找不到任何幫助。

這是操作方法登錄:

using(EntitiesModel dbContext = new EntitiesModel()) 
     { 
      try 
      { 
       string hPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "SHA1"); 

       Usuario usuario = this.rbacManager.Login(model.UserName, hPassword); 

       FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 

       if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") 
        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) 
       { 
        return Redirect(returnUrl); 
       } 
       else 
        return RedirectToAction("Index", "Home"); 

      } 
      catch (LoginIncorrectoException) 
      { 
       dbContext.SaveChanges(); 
       ViewData["Message"] = "User incorrect."; 
      } 
      catch (UsuarioBloqueadoException) 
      { 
       ViewData["Message"] = "User locked"; 
      } 

      return View(model); 
     } 

而第四行的方法登錄,拋出異常:

using (EntitiesModel context = new EntitiesModel()) 
     { 
      Usuario usuario = this.GetUsuario(username); 

      if (usuario == null) 
       throw new LoginIncorrectoException(); 

      if (!usuario.EstaActivo()) 
      { 
       throw new UsuarioBloqueadoException(); 
      } 

      if (usuario.Password != password) 
      { 
       usuario.Intentos++; 

       if (usuario.Intentos >= 3) 
       { 
        usuario.Activo = false; 
        context.SaveChanges(); 
        throw new UsuarioBloqueadoException(); 
       } 
       else 
       { 
        context.SaveChanges(); 
        throw new LoginIncorrectoException(); 
       } 
      } 

      usuario.Intentos = 0; 

      return usuario; 
     } 

編輯:我複製GetUsuario方法。

private Usuario GetUsuario(string username) 
    { 
     using (EntitiesModel context = new EntitiesModel()) 
     { 
      List<Usuario> Usuarios = context 
       .Usuarios 
       .Where(x => x.Username == username) 
       .ToList(); 

      if (Usuarios.Count == 1) 
       return Usuarios.First(); 
      else 
       throw null; 
     } 
    } 

任何人都知道爲什麼SaveChanges不起作用? 謝謝!

+0

如你所見,異常是從方法中退出,我在logOn中捕獲它。當我在三次失敗日誌之後鎖定用戶時,SaveChanges未保存在Usuario對象中修改的值,例如「usuario.Intentos ++」,當我必須增加記錄機會的計數器或「usuario.Activo = false」時。我在Login方法中這樣做。 – 2013-02-14 13:53:19

+0

你可以顯示GetUsuario方法的正文嗎? – 2013-02-14 14:00:44

回答

1

你的問題是每個方法都在創建和處理自己的DbContext。因此,當GetUser調用返回User對象時,它將從DbContext分離,因爲您已經處理它。該用戶對象的更改現在不會被保存。最直接的解決方法是將在Login方法中創建的EntitiesModel傳遞給GetUser方法。當然,你應該研究和實施更好的工作單元模式,但這應該讓你跨越障礙。您也可以將由GetUser調用返回的User對象附加到在Login調用中創建的EntitiesModel。

+0

非常感謝,我會按照您的意見 – 2013-02-15 12:57:12

1

'GetUsuario'方法創建它自己的上下文,並且'Usuario'對象由另一個上下文(已經處理)管理,因此'Login'方法中的上下文沒有掛起的更改。

您應該確保'SaveChanges'在用於首先獲取對象的相同上下文實例上調用。

+0

感謝您的回答! – 2013-02-15 12:57:54