2016-06-08 3 views
0

Getting this exceptionSaveChanges() косяк работать в C# LocalDB

Как я могу решить эту сударь, нужно решение, чтобы исправить эту

EDIT:

Я открываю мою деталь и я нашел это. Но я до сих пор не понимаю, почему PK удваивается. Подробнее: {«Нарушение ограничения PRIMARY KEY» PK_dbo.HeadMasters ». Невозможно вставить дубликат ключа в объект« dbo.HeadMasters ». Значение дублирующегося ключа равно (1). \ R \ NThe заявление было прекращено. "}

enter image description here

+1

Нажмите, чтобы просмотреть подробную информацию и показать внутреннее исключение –

+0

@RahulNikate, что я должен проверить внутри? – Student

+0

Там вы найдете внутреннее исключение. Это скажет более подробную информацию об ошибке –

ответ

0

можно переопределить метод SaveChanges на контекст. Это приведет к более подробной ошибке. На основании link, пожалуйста, найдите расширенный SaveChanges() ниже.

public override int SaveChanges() 
    { 
     try 
     { 
      return base.SaveChanges(); 
     } 
     catch (DbEntityValidationException ex) 
     { 
      // Retrieve the error messages as a list of strings. 
      var errorMessages = ex.EntityValidationErrors 
        .SelectMany(x => x.ValidationErrors) 
        .Select(x => x.ErrorMessage); 

      // Join the list to a single string. 
      var fullErrorMessage = string.Join("; ", errorMessages); 

      // Combine the original exception message with the new one. 
      var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); 

      // Throw a new DbEntityValidationException with the improved exception message. 
      throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); 
     } 
     catch (System.Data.Entity.Infrastructure.DbUpdateException ex) 
     { 
      string error = string.Format("Message: {0}, InnerException: {1}", 
           ex.Message, 
           (ex.InnerException != null ? ex.InnerException.ToString() : "") 
           ); 

      throw new Exception("DbUpdateException: " + error); 
     } 
     catch (System.Data.Entity.Core.UpdateException ex) 
     { 
      string error = string.Format("Message: {0}, InnerException: {1}", 
           ex.Message, 
           (ex.InnerException != null ? ex.InnerException.ToString() : "") 
           ); 

      throw new Exception("UpdateException: " + error); 

     } 
     catch (System.Data.SqlClient.SqlException ex) 
     { 
      string error = string.Format("Message: {0}, InnerException: {1}, SqlErrorNumber: {2}, StackTrace: {3}", 
       ex.Message, 
       (ex.InnerException != null ? ex.InnerException.Message : ""), 
       ex.Number.ToString(), 
       ex.StackTrace.ToString() 
       ); 

      throw new Exception("SqlException: " + error); 
     } 
     catch 
     { 
      throw; 
     } 
    }