首页 > 解决方案 > 删除 C 时删除 AB 之间的链接

问题描述

这是我的数据模型:

考试:

public class Exam
{
    public int Id { get; set; }
    public DateTime StartDate { get; set; }
    public int TimeLimit { get; set; }
    public User User { get; set; }
    public List<Question> Questions { get; set; }
    public QuestionSuite Suite { get; set; }
}

问题套件

public class QuestionSuite
{
    public int Id { get; set; }
    public List<Question> Questions { get; set; }
    public User Owner { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public int TimeLimit { get; set; }
}

问题

/* Some data*/
public virtual List<Exam> Exams { get; set; }
public virtual List<Result> Results { get; set; }
public virtual List<QuestionSuite> QuestionSuites { get; set; }

Question代表一个简单的问题,它的答案和东西。Exam代表当前正在进行的考试,有用户在做,一些问题,并且可能是从QuestionSuite. 最后,QuestionSuite是任何用户都可以创建和共享的自定义问题套件。

有这么多参考的原因是我需要Exam记住套件以在考试结束时通知创建者,但它仍然需要记住问题,因为并非所有考试都是从套件创建的。

现在解决问题:考试结束后,我创建一个结果,如果考试有结果,通知套件创建者,然后Exam使用以下代码删除对象:

public void DeleteExamByUserId(int userId)
{
    //Context.Exams.RemoveRange(Context.Exams.Where<Exam>(exam => exam.User.Id == userId));
    foreach(Exam e in Context.Exams)
    {
        if (e.User.Id == userId)
            Context.Exams.Remove(e);
    }
    Context.SaveChanges();
}

EntityFramework创建一个QuestionSuiteQuestions表来链接问题和套件。当一个考试被删除时,QuestionSuiteQuestions也被无端删除。

你知道为什么会这样吗?有没有办法在某处查看关系和删除背后的逻辑?

标签: c#entity-framework

解决方案


推荐阅读