【问题标题】:DbUpdateException when removing and saving changes in EF在 EF 中删除和保存更改时出现 DbUpdateException
【发布时间】:2017-04-02 00:32:45
【问题描述】:

我试图通过简单地使用 db.'table'.remove('object') 来删除数据库中的记录,但是在调用 db.SaveChanges() 时会抛出异常。

'在EntityFramework.dll中发生'System.Data.Entity.Infrastructure.DbUpdateException'类型的异常,但未在用户代码中处理'

我在控制器中的删除方法

public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Customer customer = db.Customers.Find(id);
    if (customer == null)
    {
        return HttpNotFound();
    }
    db.Customers.Remove(customer);
    db.SaveChanges();

    return RedirectToAction("Index");
}

型号:

public class Customer
{
    [Key, ForeignKey("User")]
    public int UserId { get; set; }
    public string Email { get; set; }
    public virtual CreditCard CreditCard { get; set; }
    public virtual ShoppingCart ShoppingCart { get; set; }
    public virtual List<Enquiry> Enquiries { get; set; }
    public virtual List<Order> Orders { get; set; }
    public virtual User User { get; set; }
}
public class User
{
    [Key]
    public int Id { set; get; }
    public string Username { set; get; }
    public string Password { set; get; }
    public string FirstName { set; get; }
    public string Surname { set; get; }
    public virtual UserRole UserRole { get; set; }
}

public class ShoppingCart
    {
        [Key, ForeignKey("Customer")]
        public int Id { get; set; }
        public virtual List<CartItem> CartItems { get; set; }
        public virtual Customer Customer { get; set; }
    }

部分例外:

A DbUpdateException was caught while saving changes. Type: Customer_8D9A6B7F7D247C9CB9F95E830039791E299E94FC91841FD33610DD1804AEF739 was part of the problem. 

完全例外:

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.ShoppingCarts_dbo.Customers_Id". The conflict occurred in database "MVC_COMP1562.Models.SchemaDBContext", table "dbo.ShoppingCarts", column 'Id'.
The statement has been terminated.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at MVC_COMP1562.Controllers.CustomersController.Delete(Nullable`1 id) in C:\Users\kacpe\Documents\Visual Studio 2015\Projects\MVC_COMP1562\MVC_COMP1562\Controllers\CustomersController.cs:line 165

【问题讨论】:

  • 也许您可以使用 try/catch 来获取有关异常的更多详细信息并将它们发布在这里,我们可以为您提供帮助。
  • @mako 我发现了一些我可以从异常中输出的东西,我将它添加到问题中,还有什么/如何输出更详细的信息?
  • Maybie这是一个关系问题?你试过删除而不是删除吗?stackoverflow.com/questions/17723626/…
  • @ArkadiuszRaszeja 我相信 deleteObject 在旧版本的 EF 中已被弃用
  • 如果不是您发布的内容,请发布其他异常详细信息,例如 StackTrace 和消息。

标签: asp.net-mvc entity-framework


【解决方案1】:

您似乎有另一个名为 dbo.ShoppingCarts 的关于购物车的表,其中包含与您要删除的客户相关的一行或多行。
因此,首先您必须删除与该客户相关的行,然后您才能删除该客户。发生这种情况是因为客户 ID 是该其他表中的外键。
如果情况并非如此,请将您的 ShoppingCarts 类添加到问题中。

【讨论】:

  • 在问题中添加了购物车,即使我先删除购物车,删除客户时仍然会抛出异常。
  • 可能与 Customer 和另一个表存在另一个关系。你能移植你的表格图,所有外键都可以看到吗?
  • 我现在看到你可能也和其他Tables有关系,比如InquiryOrder,如果有Foreign Keys指向Customer,那也是一样,你必须删除其他表中指向您要删除的客户的每一行。
  • 查看此链接,可能对您有所帮助:stackoverflow.com/questions/22858491/…
猜你喜欢
  • 2014-02-19
  • 1970-01-01
  • 2011-08-29
  • 2015-10-23
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多