Elena
Elena

Reputation: 839

optional optional dependent relationship EF codefirst

I have the following model:

User
id 
Document Doc1
Document Doc2


Document
Id
Data
Name

which is modelled in entity framework something like :

 modelBuilder.Entity<Document>()
                        .HasOptional(e => e.User)
                        .WithOptionalPrincipal(e => e.Doc1);

 modelBuilder.Entity<Document>()
                        .HasOptional(e => e.User)
                        .WithOptionalPrincipal(e => e.Doc2);

The idea is that user doesn't need to have these 2 documents. However when I am trying to delete a document with the following code:

 using (var ctx = new DealersContext("Db"))
    {
       var doc = ctx.Documents.FirstOrDefault(d => d.Id == docId);
       if (doc != null)
       {
         ctx.Documents.Remove(doc);
         ctx.SaveChanges();
        }

    }

I get the following error : The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.DealersUsers_dbo.Documents_IdDocument_Id". The conflict occurred in database "DealersDb", table "dbo.DealersUsers", column 'IdDocument_Id'. How can this be fixed ?

Upvotes: 0

Views: 230

Answers (1)

middelpat
middelpat

Reputation: 2585

The document still has a dealer (or a dealer still has this document) causing the database needs to set the 'IdDocument_Id to null when deleting the document from the database.

In this case 'IdDocument_Id' is not nullable. This is causing this error. You need to also remove this relation from the database, or make the dealer > document relation nullable

Upvotes: 2

Related Questions