简体   繁体   English

在ASP.NET MVC中删除对象不起作用

[英]Deleting an object in asp.net mvc doesn't work

In a controller an object is built and saved into the database. 在控制器中,将建立一个对象并将其保存到数据库中。 In the same controller action, I created another object of a different type and saved it (Class SecondType also includes an ID): 在同一控制器操作中,我创建了另一个不同类型的对象并保存了它(Class SecondType类还包括一个ID):

cDb.SecondType.Add(new SecondType { Designation = "test" });
cDb.SaveChanges();

That works. 这样可行。 When looking at index (I created the classic create, delete,... views using the scaffolding options) or detail view I can see this object and I also can modify it. 在查看索引(我使用脚手架选项创建了经典的create,delete,...视图)或局部视图时,我可以看到该对象,也可以对其进行修改。 But, if I click on delete, it shows me the first view where I have to confirm the deletion and after pressing the submit button it returns a DbUpdateException without any further information at the SaveChanges command: 但是,如果我单击删除,它将显示我必须确认删除的第一个视图,并且在按下提交按钮后,它将返回DbUpdateException而在SaveChanges命令中没有任何其他信息:

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    SecondType secondType = db.SecondTypes.Find(id);
    db.SecondTypes.Remove(secondType);
    db.SaveChanges();
    return RedirectToAction("Index");
}

I don't know why this happens and I would be very thankful if you have any ideas to fix this. 我不知道为什么会这样,如果您有任何解决办法,我将非常感谢。

This is what I could copy: 这是我可以复制的内容:

System.Data.Entity.Infrastructure.DbUpdateException ist aufgetreten.
HResult=-2146233087
Message=Fehler beim Aktualisieren der Einträge (= Error while updating the entries). Weitere Informationen  finden Sie in der internen Ausnahme.
  Source=EntityFramework
  StackTrace:
   bei System.Data.Entity.Internal.InternalContext.SaveChanges()
   bei System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   bei System.Data.Entity.DbContext.SaveChanges()
   bei Irgendwas.Controllers.SecondTypeController.DeleteConfirmed(Int32 id) in c:\Users\username\Documents\Visual Studio 2012\Projects\Irgendwas\Irgendwas\Irgendwas\Controllers\SecondTypeController.cs:Zeile 113.
  InnerException: System.Data.UpdateException
   HResult=-2146233087
   Message=Fehler beim Aktualisieren der Einträge. Weitere Informationen finden Sie in der internen Ausnahme.
   Source=System.Data.Entity
   StackTrace:
        bei System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
        bei System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
        bei System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
        bei System.Data.Entity.Internal.InternalContext.SaveChanges()
        InnerException: System.Data.SqlClient.SqlException
        HResult=-2146232060
        Message=Die DELETE-Anweisung steht in Konflikt mit der REFERENCE-Einschränkung 'FK_dbo.ThirdTypes_dbo.Second_SecondType_ID'. Der Konflikt trat in der 'Irgendwas.Models.SecondTypeContext'-Datenbank, Tabelle 'dbo.ThirdTypes', column 'SecondType_ID' auf.
Die Anweisung wurde beendet.
        Source=.Net SqlClient Data Provider
        ErrorCode=-2146232060
        Class=16
        LineNumber=1
        Number=547
        Procedure=""
        Server=.\SQLEXPRESS
        State=0
        StackTrace:
             bei System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
             bei System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
             bei System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
             bei System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
             bei System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
             bei System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
             bei System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
             bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
             bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
             bei System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
             bei System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
        InnerException: 

My german is a bit rough but I think you have entries in your dbo.ThirdTypes table that reference the entry you try to delete from the dbo.SecondTypes table. 我的德语有点粗糙,但是我认为您在dbo.ThirdTypes表中有一些条目,这些条目引用了您尝试从dbo.SecondTypes表中删除的条目。

Try to remove all dbo.ThirdTypes entries that reference the dbo.SecondTypes before you remove the secondType entry and call SaveChanges(). 尝试删除所有引用dbo.SecondTypes的dbo.ThirdTypes条目,然后再删除secondType条目并调用SaveChanges()。

Like so: 像这样:

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    SecondType secondType = db.SecondTypes.Find(id);

    foreach (var thirdType in secondType.ThirdTypes)
    {
        db.ThirdTypes.Remove(thirdType);
    }

    db.SecondTypes.Remove(secondType);
    db.SaveChanges();
    return RedirectToAction("Index");
}

You can also enable Cascade Delete on the relation in your database. 您还可以在数据库中的关系上启用“级联删除”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM