I ran into an interesting problem (hopefully, interesting not just for me :)
I am running Entity Framework 1 (.NET 3.5) and ASP.NET MVC 2. I have a Customer class that has many-to-one relationship with Country class (in other words, Country is a lookup table for customers - I described more in this post: http://stackoverflow.com/questions/2404801/explicit-casting-doesnt-work-in-default-model-binding )
I got TypeConverter to work; so I am getting a perfect object into controller's Post method. Create works fine; however, in Edit I am getting the following error when I call ApplyPropertyChanges:
The existing object in the ObjectContext is in the Added state. Changes can only be applied when the existing object is in an unchanged or modified state.
The controller code is fairly trivial:
public ActionResult Edit(Customer customerToEdit) {
if (ModelState.IsValid) {
Customer cust = (Customer)context.GetObjectByKey(
new EntityKey("BAEntities.Customers", "CustomerID", customerToEdit.CustomerID));
context.ApplyPropertyChanges(cust.EntityKey.EntitySetName, customerToEdit);
context.SaveChanges();
}
return View(...);
}
If I remove country from the form, it works fine; and if I assign dropdown value to EntityReference "manually" - it works as well.
TypeConverter code is also fairly simple, but I've never used TypeConverter before, so I may be missing something here:
public override object ConvertFrom(ITypeDescriptorContext typeContext, CultureInfo culture, object value) {
if (value is string) {
int countryID = Int16.Parse((string)value);
Country country = (Country)context.GetObjectByKey(
new EntityKey("BAEntities.Countries", "CountryID", countryID));
return country;
}
return base.ConvertFrom(typeContext, culture, value);
}