0

When submitting a form and passing in my model (Forms) I am trying to save the changes to my DB.

Forms model has a PeopleInvolved object as a property.

The model is updated successfully, the changes also get added to the peopleInvolved object successfully, however, the SaveChanges() call doesn't save anything.

.NET Framework 4.5.1 - EF 6.1.1

public class Forms
{
        public int Id { get; set; }
        public string UserId { get; set; }
        public PeopleInvolved PeopleInvolved { get; set; }     
}

public async Task<ActionResult> EditForm(Forms model, string returnUrl)
{
    ViewData["ReturnUrl"] = returnUrl;
    ApplicationUser user = await GetCurrentUserAsync();

    if (!ModelState.IsValid) 
        return RedirectToAction("Index", model);

    if (model.PeopleInvolved != null)
    {
        PeopleInvolved peopleInvolved = _db.PeopleInvolved.Single(x => x.FormId == user.FormId);
        peopleInvolved = model.PeopleInvolved;

        _db.SaveChanges();

        return RedirectToLocal(returnUrl + "?PeopleInvolved?Success");
    }
}
2
  • Are you trying to add or update? Commented Nov 15, 2016 at 21:40
  • I'm trying to update - ideally without having to manually assign each property to corresponding model property. Commented Nov 15, 2016 at 21:45

2 Answers 2

1

You didn't actually change anything from the database.

Your call to the database returned a PeopleInvolved object and stored a reference to it in the peopleInvolved variable. Then you change that variable to be a reference to the PeopleInvolved property on the model object. You never actually change the object returned from the database call.

Simplistic solution is to do something like

peopleInvolved.Property1 = model.PeopleInvolved.Property1;
peopleInvolved.Property2 = model.PeopleInvolved.Property2;

to update the actual object that was returned from the database.

Sign up to request clarification or add additional context in comments.

1 Comment

ARGH you are totally correct! I was trying to get around assigning each property individually. Thank you!
0

You can update like this. If you have to override model.PeopleInvolved.FormId with user.FormId update that property.

db.PeopleInvolved.Attach(model.PeopleInvolved);
db.Entry(model.PeopleInvolved)).State =  System.Data.Entity.EntityState.Modified;    
db.SaveChanges();

1 Comment

Awesome, works a charm - I already tried this but AFTER I'd retrieved a row so was getting a duplicate primary key. Thank you :D

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.