0

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);
}
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425

1 Answers1

3

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();
Navoneel Talukdar
  • 3,964
  • 4
  • 19
  • 39