2017-03-21 1 views
0

나는 dbContextwhich 사용자가 올바른지 데이터베이스와 확인 후 다음dbcontext 절약도 exeption

public class DbContext: System.Data.Entity.DbContext 
{ 
    public DbSet<UserAccount> UserAccounts { get; set; } 
    public DbSet<Sesison> Sessions { get; set; } 
} 

으로 그리고 어떤 이유로 내 로그인 행동에 설명되어 사용하고 잡기하지 내가 사용할 수 아니다 데이터베이스에 저장하는 컨텍스트의 다른 엔티티, 무슨 일이 나는 데이터를 데이터베이스에 저장되지 않습니다 및 실제로 dc.SaveChanges() 후 코드 실행을 중지합니다 있지만 내 catch, 그래서 내 브라우저가 만료되는 것은 500 내부 서버 오류입니다.

public ActionResult Login(LoginViewModel model) 
    { 
     using (DbContext dc = new DbContext()) 
     { 
      var v = dc.UserAccounts.SingleOrDefault(a => a.UserName == model.UserName); 
      if (v != null) 
      { 
       if (GetSHA1(model.Password) == v.Password) 
       { 
        Guid sessionGuid =Guid.NewGuid(); 
        var session = dc.Sessions.Add(new Sesison() { SessionID = sessionGuid,StartDateTime=DateTime.UtcNow,UserID = v.UserID,ExpireDateTime=DateTime.UtcNow.AddHours(4)}); 
        System.Web.HttpContext.Current.Session["IsLogin"] = true; 
        System.Web.HttpContext.Current.Session["Session"] = sessionGuid; 
        try 
        { 
         dc.SaveChanges(); 
        } 
        catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) 
        { 
         Exception raise = dbEx; 
         foreach (var validationErrors in dbEx.EntityValidationErrors) 
         { 
          foreach (var validationError in validationErrors.ValidationErrors) 
          { 
           string message = string.Format("{0}:{1}", 
            validationErrors.Entry.Entity.ToString(), 
            validationError.ErrorMessage); 
           // raise a new exception nesting 
           // the current instance as InnerException 
           raise = new InvalidOperationException(message, raise); 
          } 
         } 
         throw raise; 
        } 
        return Json(new 
        { 
         Item1 = "true" 

        }); 
       } 
       else 
       { 
        return Json(new 
        { 
         Item1 = "false", 
         Item2 = "The username or password you entered is incorrect. Please try again." 
        }); 
       } 
      } 
      else 
      { 
       return Json(new 
       { 
        Item1 ="false", 
        Item2 = "The username or password you entered is incorrect. Please try again." 
       }); 
      } 

     } 
     return null; 
    } 
+0

500 내부 서버 오류 쇼를, 무엇 때문에 그게 내가 그렇지 않은 것을 말할 것입니다 무슨 일이 일어나고 있는지의 경우'당신이 시도하고 저장할 때 System.Data.Entity.Validation.DbEntityValidationException'가 발생된다. –

+0

jquery –

+0

에서 runned 이후 consle에 그것을 얻은 이후로 나는 잘 모르겠다. jorery를 출력하기 위해 jquery를 약간 변경했다. INSERT 문은 FOREIGN KEY 제약 조건 "FK_Session_Users"과 충돌했다. 데이터베이스 "FuelSensorDev", 테이블 "dbo.Users", 열 'id'에서 충돌이 발생했습니다. 명세서가 종료되었습니다. –

답변

1

SaveChanges를에 대한 호출이 DbEntityValidationException

가 아닌 다른 유형의 예외를 던지고있다

DbContext SaveChanges를 호출 얼핏는 예외 다음과 같은 유형을 던질 수 있음을 보여줍니다. 각각을 처리하고 싶지 않으면 문제를 찾기 위해 일반적인 Exception 처리를 추가하고 싶을 것입니다.

// Exceptions: 
    // T:System.Data.Entity.Infrastructure.DbUpdateException: 
    //  An error occurred sending updates to the database. 
    // 
    // T:System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: 
    //  A database command did not affect the expected number of rows. This usually indicates 
    //  an optimistic concurrency violation; that is, a row has been changed in the database 
    //  since it was queried. 
    // 
    // T:System.Data.Entity.Validation.DbEntityValidationException: 
    //  The save was aborted because validation of entity property values failed. 
    // 
    // T:System.NotSupportedException: 
    //  An attempt was made to use unsupported behavior such as executing multiple asynchronous 
    //  commands concurrently on the same context instance. 
    // 
    // T:System.ObjectDisposedException: 
    //  The context or connection have been disposed. 
    // 
    // T:System.InvalidOperationException: 
    //  Some error occurred attempting to process entities in the context either before 
    //  or after sending commands to the database.