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

前端 未结 3 708
野的像风
野的像风 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:01

    It looks like there is a Parent entity that has a one to many relationship with your Consultant entity. When you change an attribute of the Consultant entity that is used as the ForeignKey for that relationship, Entity Framework sets the relevant field in the Parent entity to null to decouple the relationship. When that field is not nullable you'll get this error. Actually that error definition is surprisingly good, I've seen this problem with far more cryptic errors.

    So, I recommend that you check the parent entity in the database, and proceed to a remedy from there (if you can change it to nullable all is well, if it is part of a different constraint -pk or suchlike- you'll have to fiddle with your object models). I'd ask you to post your entity models, but the chunk of text is intimidating as it is.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-06 17:13

    I think the error you are getting is related to: EF 4: Removing child object from collection does not delete it - why? You have created an orphan somewhere.

    0 讨论(0)
提交回复
热议问题