I have problems updating a child object of my POCO with CodeFirst. My POCO's are the following
public class Place { public int ID { get; set; public string Name { get; set; } public virtual Address Address { get; set; } } public class Address { public int ID { get; set; public string AddressLine { get; set; } public string City { get; set; } public virtual State State { get; set; } } public class State { public int ID { get; set; public string Name { get; set; } } I have a view to edit all fields of place and its childs. All properties are textbox except for State that is a DropDownList.
When user clicks so save button the view returns all Place properties filled, except State that is filled only with ID because it's value come from a DropDownList and Name is empty.
In Edit Post Method I have the following code:
if (ModelState.IsValid) { bool isNewPlace = place.ID == -1; //Hack, State name is empty from View, we reload place.Address.State = new StateBLL().GetByID(place.Address.State.ID); new PlaceBLL().Update(place); return RedirectToAction("Index"); } And Update code from PlaceBLL class is the following
protected override void Update(Place place) { MyDbContext.Instance().Set<Address>().Attach(place.Address); MyDbContext.Instance().Entry(place.Address).State = System.Data.EntityState.Modified; MyDbContext.Instance().Set<State>().Attach(place.Address.State); MyDbContext.Instance().Entry(place.Address.State) = System.Data.EntityState.Modified; MyDbContext.Instance().SaveChanges(); } When the user edit Place object all fields are update correctly except state, when the user change the state of some place, this change isn't persisted to database, if seems that Code first not detects state change from user.
Do you know why code first doesn't detect State change value from a Place?
Thanks.