Entity Framework Error Deleting Entity with Foreign Key Relationship

entity-framework entity-framework-6 poco

Question

I am having a problem deleting some entities due to a foreign key relationship. I understand the following error message and have been doing everything I can think of to delete the entities without incurring this error:

The DELETE statement conflicted with the REFERENCE constraint "FK_QuizUserAnswer_QuizWithQuestion". The conflict occurred in database "SomeDatabase", table "dbo.QuizUserAnswer", column 'idQuizQuestion'. The statement has been terminated.

Here is an image of the two tables in question:

enter image description here

I am trying to delete QuizWithQuestion entities. I have made the idQuizQuestion column nullable. So, the foreign key is nullable on the QuizUserAnswer side. In the mapping files, I have specified that the relationship is optional:

HasMany(t => t.QuizUserAnswers)
    .WithOptional(t => t.QuizWithQuestion)
    .HasForeignKey(t => t.idQuizQuestion);

HasOptional(t => t.QuizWithQuestion)
    .WithMany(t => t.QuizUserAnswers)
    .HasForeignKey(d => d.idQuizQuestion);

I have tried many, many snippets of code, so I will post the current state of the code in the hope that my intention is clear:

    public void RemoveQuestionsFromQuiz(IEnumerable<int> deletedQuestions, int quizId)
    {
        var quiz = // code which retrieves quiz

        foreach (var deletedQuestion in deletedQuestions)
        {
            var quizWithQuestion = quiz.QuizWithQuestions.FirstOrDefault(q => q.Id == deletedQuestion);

            if (!ReferenceEquals(null, quizWithQuestion))
            {
                db.Entry(quizWithQuestion).State = EntityState.Deleted;                    
            }
        }
        db.SaveChanges();
    }

Another attempt looks like this:

public void RemoveQuestionsFromQuiz(IEnumerable<int> deletedQuestions, int quizId)
{
    var quiz = // code which retrieves quiz

    foreach (var deletedQuestion in deletedQuestions)
    {
        var quizWithQuestion = quiz.QuizWithQuestions.FirstOrDefault(q => q.Id == deletedQuestion);

        if (!ReferenceEquals(null, quizWithQuestion))
        {
            foreach (var quizUserAnswer in quizWithQuestion.QuizUserAnswers)
            {
                quizUserAnswer.idQuizQuestion = null; // nullable
                quizWithQuestion.QuizUserAnswers.Remove(quizUserAnswer);
                db.Entry(quizUserAnswer).State = EntityState.Modified;
            }

            quiz.QuizWithQuestions.Remove(quizWithQuestion);

            db.Entry(quizWithQuestion).State = EntityState.Deleted;
        }
    }
    _db.SaveChanges();
}

How can I delete these darn entities (I'm so close to writing a stored procedure)?

1
3
5/20/2015 1:52:19 PM

Accepted Answer

Since you already have the question ids to delete, something like this should work:

// assuming db is your DbContext
var questions = db.QuizWithQuestions
                  .Where(q => deletedQuestions.Contains(q.Id))
                  .Include(q => q.QuizUserAnswers);

// assuming this is your DbSet
db.QuizWithQuestions.RemoveRange(questions);

db.SaveChanges();

If the QuizUserAnswer entities are loaded into the context (which is what include should do), Entity Framework should handle setting the foreign keys to null.

4
5/21/2015 12:42:51 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow