I am trying to update a complex model in a single view. I am using ASP.NET MVC3, Entity Framework with Code first, unit of work, generic repository pattern.. but when I try to update the model, i come up with this error:
A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
Here is my simplified view model:
public class TransactionViewModel
{
public Transaction Transaction { get; set; }
public bool IsUserSubmitting { get; set; }
public IEnumerable<SelectListItem> ContractTypes { get; set; }
}
Here is my simplified complex model, and as an example one of its navigation property. Transaction has one to one relationship with all of its navigation properties:
public class Transaction
{
[Key]
public int Id { get; set; }
public int CurrentStageId { get; set; }
public int? BidId { get; set; }
public int? EvaluationId { get; set; }
public virtual Stage CurrentStage { get; set; }
public virtual Bid Bid { get; set; }
public virtual Evaluation Evaluation { get; set; }
}
public class Bid
{
[Key]
public int Id { get; set; }
public string Type { get; set; }
public DateTime? PublicationDate { get; set; }
public DateTime? BidOpeningDate { get; set; }
public DateTime? ServiceDate { get; set; }
public string ContractBuyerComments { get; set; }
public string BidNumber { get; set; }
public DateTime? ReminderDate { get; set; }
public DateTime? SubmitDate { get; set; }
}
Using the same view model, I am able to create a transaction object, which would populate the database like this.
Id: 1, CurrentStageId: 1, BidId: 1, EvaluationId: 1
but, when I try to update properties within these navigation properties, this line causes the error, in controller:
[HttpPost]
public ActionResult Edit(TransactionViewModel model)
{
if (ModelState.IsValid)
{
-> unitOfWork.TransactionRepository.Update(model.Transaction);
unitOfWork.Save();
return RedirectToAction("List");
}
}
In generic repository:
public virtual void Update(TEntity entityToUpdate)
{
-> dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
The problem is further complicated because I should be able to edit any of the fields(properties) within any of the navigation property within Transaction object within a single view.
Now let’s understand how to use the TryUpdateModel function in ASP.NET MVC Application. Modify the create (HttpPost) action method as shown below. Here we use TryUpdateModel () instead of UpdateModel (). Now run the application and see everything is working as expected.
Step 1: Create an MVC Application. "Start", then "All Programs" and select "Microsoft Visual Studio 2015". "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
Choose the "web application" project and give an appropriate name for your project. Select "empty" template, check the MVC checkbox, and click OK. Right-click the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.
The difference is UpdateModel () throws an exception if validation fails whereas TryUpdateModel () will never throw an exception. The similarity is both the functions are used to update the Model with the Form values and perform the validations. Is it mandatory to use “UpdateModel ()” or “Try”UpdateModel ()” function to update the Model?
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:
Update
method of your repository (=hack)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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With