How to update complex model in ASP.NET MVC 3

假如想象 提交于 2019-11-30 09:50:32

I believe that the exception means the following:

The property values that define the referential constraints ... (these are the primary key property (= Id) value of Bid and the foreign key property (= BidId) value of Transaction)

... are not consistent ... (= have different values)

... between principal ... (= Bid)

... and dependent ... (= Transaction)

... objects in the relationship.

So, it looks like the following: When the MVC model binder creates the TransactionViewModel as parameter for the Edit action, model.Transaction.BidId and model.Transaction.Bid.Id are different, for example:

  • model.Transaction.BidId.HasValue is true but model.Transaction.Bid is null
  • model.Transaction.BidId.HasValue is false but model.Transaction.Bid is not null
  • model.Transaction.BidId.Value != model.Transaction.Bid.Id

(The first point is probably not a problem. My guess is that you have situation 2.)

The same applies to CurrentStage and Evaluation.

Possible solutions:

  • Set those properties to the same values before you call the Update method of your repository (=hack)
  • Bind TransactionViewModel.Transaction.BidId and TransactionViewModel.Transaction.Bid.Id to two hidden form fields with the same value so that the model binder fills both properties.
  • Use also a ViewModel for your inner Transaction property (and for the navigation properties inside of Transaction as well) which is tailored to your view and which you can map appropriately to the entities in your controller action.

One last point to mention is that this line ...

context.Entry(entityToUpdate).State = EntityState.Modified;

... does not flag the related objects (Transaction.Bid) as modified, so it would not save any changes of Transaction.Bid. You must set the state for the related objects to Modified as well.

Side note: If you don't have any additional mapping with Fluent API for EF all your relationships are not one-to-one but one-to-many because you have separate FK properties. One-to-One relationships with EF require shared primary keys.

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