Entity Framework and MVC 3: The relationship could not be changed because one or more of the foreign-key properties is non-nullable

前端 未结 3 739
野的像风
野的像风 2021-01-06 16:30

I have been trying to use one View for updating an object and all its child collections (based on one-to-many relationships in an SQL Server database with an Entity Framewor

3条回答
  •  既然无缘
    2021-01-06 17:05

    Yes it is related to HtmlPrefixScopeExtensions, but only because you are using Mvc Futures model binders. In global.asax.cs comment out the line

    Microsoft.Web.Mvc.ModelBinding.ModelBinderConfig.Initialize(); 
    

    and retry: it will work ok !

    The problem happens because the MVC futures model binder does not handle correctly this case. It converts ok the form data into your model when you submit the form, but it has a problem when filling the ModelState object when you use HtmlPrefixScopeExtensions to generate non incremental ids.

    The model itself is correctly created from the form data. The problem lies inside ModelState which contains only the last value of the collection instead of all elements of the collection.

    The strongly typed helper method - which renders the list - only select items which are in your Model property list AND in the matching ModelState entry which is converted into a list. So because there is only one item in the matching ModelState entry other list items get deselected.

    This method called by the strongly typed helper code:

    htmlHelper.GetModelStateValue(fullName, typeof(string[]))
    

    returns only the last element of the list, because ModelState["Programs[cabac7d3-855f-45d8-81b8-c31fcaa8bd3d].List"].Value contains only the last element of the list.

    This is a bug (or non supported scenario) in MVC3 Futures extensible model binders.

提交回复
热议问题