TypeConverter prevents ApplyPropertyChanges in EntityFramework

霸气de小男生 提交于 2019-12-11 02:27:48

问题


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: Explicit casting doesn't 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?

来源:https://stackoverflow.com/questions/2443062/typeconverter-prevents-applypropertychanges-in-entityframework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!