简体   繁体   中英

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.

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 can only save child objects if the parent object is retrieved with the same context.

As a solution you need to explicitly iterate over your child properties and set its state to modified.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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