尝试更新分离的实体的相关集合时,集合重复

时间:2014-09-30 15:18:11

标签: c# asp.net entity-framework entity-framework-6 asp.net-web-api2

我有两个API调用。 GetExam和SaveExam。 GetExam序列化为JSON,这意味着当我去保存时,实体被分离。这不是问题,我可以通过其主键检索实体并手动更新其属性。

但是,当我这样做时,考试问题会重复当前的收藏。例如,如果exam​​ToSave.ExamQuestions删除了一些问题,并且添加了一个新问题,则所有selectedExam.exam_question都会重复,并且会添加新的问题。例如。如果存在3个问题,我删除1并添加4,现在将有7个。

域名模型:

public partial class exam
{
    public exam()
    {
        this.exam_question = new HashSet<exam_question>();
    }

    public int ID { get; set; }
    public string ExamName { get; set; }
    public string ExamDesc { get; set; }
    public Nullable<decimal> TimeToComplete { get; set; }
    public bool AllowBackStep { get; set; }
    public bool RandomizeAnswerOrder { get; set; }
    public int Attempts { get; set; }

    public virtual ICollection<exam_question> exam_question { get; set; }
}

public partial class exam_question
{
    public exam_question()
    {
        this.exam_answer = new HashSet<exam_answer>();
    }

    public int ID { get; set; }
    public int ExamID { get; set; }
    public string QuestionText { get; set; }
    public bool IsFreeForm { get; set; }

    public virtual exam exam { get; set; }
    public virtual ICollection<exam_answer> exam_answer { get; set; }
}

public partial class exam_answer
{
    public int ID { get; set; }
    public string AnswerText { get; set; }
    public int QuestionID { get; set; }
    public bool IsCorrect { get; set; }

    public virtual exam_question exam_question { get; set; }
}

保存方法:

[Route("SaveExam")]
[HttpPost]
public IHttpActionResult SaveExam(ExamViewModel examToSave)
{
    using (var db = new IntranetEntities())
    {
        // try to locate the desired exam to update
        var selectedExam = db.exams.Where(w => w.ID == examToSave.ID).SingleOrDefault();

        if (selectedExam == null)
        {
            return NotFound();
        }

        // Redacted business logic

        // Map the viewmodel to the domain model
        Mapper.CreateMap<ExamAnswerViewModel, exam_answer>();
        Mapper.CreateMap<ExamQuestionViewModel, exam_question>().ForMember(dest => dest.exam_answer, opt => opt.MapFrom(src => src.QuestionAnswers));
        Mapper.CreateMap<ExamViewModel, exam>().ForMember(dest => dest.exam_question, opt => opt.MapFrom(src => src.ExamQuestions));
        var viewmodel = Mapper.Map<exam>(examToSave);

        // Update exam properties
        selectedExam.ExamName = viewmodel.ExamName;
        selectedExam.ExamDesc = viewmodel.ExamDesc;
        selectedExam.AllowBackStep = viewmodel.AllowBackStep;
        selectedExam.Attempts = viewmodel.Attempts;
        selectedExam.RandomizeAnswerOrder = viewmodel.RandomizeAnswerOrder;
        selectedExam.exam_question = viewmodel.exam_question; // DUPLICATES PROPS

        // Save 
        db.SaveChanges();

        return Ok(examToSave);
    }

}

0 个答案:

没有答案