实体框架错误删除具有外键关系的实体

时间:2015-05-20 13:52:20

标签: entity-framework entity-framework-6 poco

由于外键关系,我在删除某些实体时遇到问题。我理解以下错误消息,并且一直在做我能想到的删除实体而不会引发此错误:

  

DELETE语句与REFERENCE约束冲突   " FK_QuizUserAnswer_QuizWithQuestion&#34 ;.冲突发生在   数据库" SomeDatabase",table" dbo.QuizUserAnswer",列   ' idQuizQuestion&#39 ;.声明已经终止。

以下是两个表格的图片:

enter image description here

我正在尝试删除 QuizWithQuestion 实体。我已将idQuizQuestion列设为可以为空。因此,外键在QuizUserAnswer端可以为空。 在映射文件中,我已指定关系为可选

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

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

我已经尝试了很多很多代码片段,所以我会发布代码的当前状态,希望我的意图很明确:

    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();
    }

另一种尝试看起来像这样:

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();
}

如何删除这些darn实体(我非常接近于编写存储过程)?

1 个答案:

答案 0 :(得分:4)

由于你已经有了要删除的问题ID,所以这样的事情应该有效:

// 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();

如果QuizUserAnswer实体被加载到上下文中(包括应该做什么),Entity Framework应该处理将外键设置为null。