SaveChanges()无法在C#localdb中运行

时间:2016-06-08 09:24:08

标签: c# entity-framework localdb

Getting this exception

我如何解决这个先生,需要解决方案来解决这个问题

编辑:

我打开细节,发现了这个。但我仍然不明白为什么PK加倍 细节:{"违反PRIMARY KEY约束' PK_dbo.HeadMasters'。无法在对象' dbo.HeadMasters'中插入重复键。重复键值为(1)。\ r \ n语句已终止。"}

enter image description here

1 个答案:

答案 0 :(得分:0)

可以在上下文中覆盖SaveChanges方法。这将导致更详细的错误。根据{{​​3}},请在下面找到扩展的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;
        }
    }