How-To: Perform Update Actions using an ObjectContainerDataSource with Entity Framework
The P&P Sustained Engineering team has published an article in the Known Issues / Fixes section of the WCSF Knowledge Base about how to perform updates objects from an ObjectContainterDataSource (OCDS) using Entity Framework (EF) correctly.
When using OCDS connected to an Entity Data Model (EDM), and try to accept the updates effectuated, no changes will be seen in the next postback. The cause of the problem is that the OCDS creates a new instance of the objects (entities) in each action performed and these are not binding correctly with the EF.
A possible workaround to solve this issue is modifying the Updated event raised by the OCDS to perform the following steps:
- Retrieve the entity from the EDM again (to accomplish this we can use the Entity’s EntityKey property, that identifies the object and is like the primary key in the Relational Model).
- Set the properties changed in the entity passed by the Updated event to the entity retrieved from the EDM.
- Accept the change made in the model.
A code example of this can be found below:
public void OnOCDSUpdated(Model.Entity1 updatedEntity)
{
Model.EDM ent = newModel.EDM();
//retrieve the entity from the EDM (by primary key)
Model.Entity1 aux = ent.GetObjectByKey(updatedEntity.EntityKey) asModel.Entity1;
if(aux != null)
{
//overwrite the mapped values in the entity retrieved from the EDM
aux.Property1 = updatedEntity.Property1;
aux.Property2 = updatedEntity.Property2;
}
ent.SaveChanges();
}
The key of the solution is retrieving the object again from the EDM, this causes the EF’s properties in the retrieved object to be loaded correctly. Then, when we change the values in the properties of the object, so the EF knows about this. In this way, when we accept the changes done, the new values will be updated in the Database.
We also made a sample application to solve the problem. You can download it from here. Pay attention to the README.txt file and the prerequisites inside this, to run the solution without problems.
I hope you can find this useful and I would like to receive your suggestions and comments.
Greetings,
Eze