在DB中附加到IList会使用MVC中的EF引发引用完整性约束冲突



我有这样设置的POCO类:

public class Survey
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual IList<Image> Images { get; set; }
}
public class Image
{
    [Key]
    public int ImageID { get; set; }
    public int SurveyID { get; set; }
    public string ImageUrl { get; set; }
    public virtual Survey Survey { get; set; }
}

我可以在数据库中创建条目,其中所有字段都设置得当。当我试图编辑图像中的项目时,我会遇到引用完整性约束冲突。例如,我最初创建了带有2个图像的数据。在编辑中,我将另一张图像添加到集合中。在编辑视图中,我只设置ImageUrl,因为我希望EF在保存时使用创建适当的ImageID和SurveyID

 db.Entry(survey).State = EntityState.Modified;
 db.SaveChanges();

我已检查Image[0]和1].ImageId、SurveyID、ImageUrl是否已正确绑定。Image[2]、ImageId和SurveyID被设置为0,但我希望EF在将其保存到DB时设置它们。

我已经使用modelbuilder对选项进行了尝试,但有些地方我做得不对。非常感谢你的帮助。

这是我得到的错误:附加信息:发生引用完整性约束冲突:关系一端的"Survey.ID"属性值与"Image.SurveyID"的属性值不匹配

编辑编辑附加的代码

    public ActionResult Edit([Bind(Include = "ID,Name, Images")] Survey survey)
    {
        if (ModelState.IsValid)
        {
            db.Entry(survey).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(survey);
    }

我能够通过在编辑操作结果中单独添加图像来解决这个问题。

    public ActionResult Edit([Bind(Include = "ID,Name,Images")] Survey survey)
    {
        if (ModelState.IsValid)
        {
            for (var i = 0; i < survey.Images.Count; i++ )
            {
                if ((survey.Images[i].SurveyID == 0) && (survey.Images[i].ImageID == 0))
                {
                    survey.Images[i].SurveyID = survey.ID;
                    db.Images.Add(survey.Images[i]);
                }
            }
            db.Entry(survey).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(survey);
    }

最新更新