Entity Framework Error Deleting Entity with Foreign Key Relationship

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-14 01:47:21

问题


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:

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:


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.



来源:https://stackoverflow.com/questions/30351762/entity-framework-error-deleting-entity-with-foreign-key-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!