Get duplicate key exception when deleting and re-adding child rows in Entity Framework

I use the Entity Framework to model a simple parent child link between a document and its pages. The following code should (in that order):

  • make several changes to the document properties.
  • delete any of the existing document pages
  • insert a new list of pages passed to this method.

New pages have the same keys as deleted pages, because there is an index that consists of the document number and then the page number (1..n).

This code works. However, when I delete the first call to SaveChanges, it fails with:

System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 
'dbo.DocPages' with unique index 'IX_DocPages'.

Here is the working code with two SaveChanges calls:

        Document doc = _docRepository.GetDocumentByRepositoryDocKey(repository.Repository_ID, repositoryDocKey);

        if (doc == null) {
            doc = new Document();
            _docRepository.Add(doc);
        }
        _fieldSetter.SetDocumentFields(doc, fieldValues);

        List<DocPage> pagesToDelete = (from p in doc.DocPages
                                       select p).ToList();

        foreach (DocPage page in pagesToDelete) {
            _docRepository.DeletePage(page);
        }

        _docRepository.GetUnitOfWork().SaveChanges();  //IF WE TAKE THIS OUT IT FAILS

        int pageNo = 0;
        foreach (ConcordanceDatabase.PageFile pageFile in pageList) {
            ++pageNo;
            DocPage newPage = new DocPage();
            newPage.PageNumber = pageNo;
            newPage.ImageRelativePath = pageFile.Filespec;
            doc.DocPages.Add(newPage);
        }

        _docRepository.GetUnitOfWork().SaveChanges();  //WHY CAN'T THIS BE THE ONLY CALL TO SaveChanges

, EF - SaveChanges. . . SQL, , .

, SaveChanges ( , ), EF , ? - . , SaveChanges ?

, _docRepository.DeletePage() objectContext.DeleteObject(). - ? .

+3
2

, , EF , , , , .

, , DbCommands .

, SaveChanges().

TransactionScope.

SaveChanges(), .

. .

,

+4

, . . , SaveChanges() - , , - , , , . SaveChanges (false) - EF, , , , . scope.Complete(), EF.AcceptAllChanges(). , , SaveChanges TWICE . SaveChanges False accept changes, , SQL . , Catch-22.

0

Source: https://habr.com/ru/post/1719659/


All Articles