views:

207

answers:

0

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. UPDATE: it looks that if I don't have lookup field, customerToEdit is in Unchanged state (as I expect); however, if the lookup is there and TypeConverter is invoked - the object is now in Added state. So, the ultimate question is, how can I prevent the object from becoming Added while still using TypeConverter...

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

UPDATE 2: FWIW, I can see that the state gets changed when DefaultModelBinder::SetProperty is calling propertyDescriptor.SetValue(bindingContext.Model, value); Since PropertyDescriptor is not part of MVC, I can't debug any further. Anybody knows why PropertyDescriptor marks Model as "added" and what can I do about it?