简体   繁体   English

无法使用实体框架更新子实体

[英]Unable to update child entity using Entity Framework

These are my model classes. 这些是我的模型类。

public class Survey
{
    [Key]
    public int SurveyID { get; set; }
    [Required]
    public string Title { get; set; }
    [DataType(DataType.Text)]
    [Required]
    public string Description { get; set; }
    public virtual Category Category { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    public string CategoryText { get; set; }
}

In the edit action of the SurveyController the survey properties are updating but not the category. SurveyController的编辑操作中,测量属性正在更新,但类别没有更新。

Here is the edit action code. 这是编辑操作代码。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Survey survey)
{
    db.Database.Log = s => Debug.WriteLine(s);

    if (ModelState.IsValid)
    {
        db.Entry(survey).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(survey);
}

Entity framework by default does not update the navigation properties. 默认情况下,实体框架不会更新导航属性。 EF only knows/tracks the changes in the properties you explicitly update. EF仅知道/跟踪您显式更新的属性中的更改。 EF can only save child objects if the parent object is retrieved with the same context. 如果使用相同上下文检索父对象,则EF只能保存子对象。

As a solution you need to explicitly iterate over your child properties and set its state to modified. 作为解决方案,您需要显式遍历子属性并将其状态设置为Modifyed。

Sample code 样例代码

 foreach (var childModel in model.Children)
    {
        var existingChild = existingParent.Children
            .Where(c => c.Id == childModel.Id)
            .SingleOrDefault();

        if (existingChild != null)
           _dbContext.Entry(existingChild).CurrentValues.SetValues(childModel);
    }

Update 更新

var child = new ChildEntity() {Id = 1};
child.ParentEntityId = 1;  // Assigning FK
context.Childs.Attach(child);
context.Entry(child).State = EntityState.Modified;
context.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM