-1

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):

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. 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:

[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: 
Underfaker
  • 97
  • 2
  • 12

1 Answers1

2

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.

Try to remove all dbo.ThirdTypes entries that reference the dbo.SecondTypes before you remove the secondType entry and call 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.

Wessel T.
  • 2,280
  • 2
  • 20
  • 29