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);
}
3

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

I just want to update the foreign key of the survey entity

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.