How-To: Perform Update Actions using an Object Container Data Source with Entity Framework

Contents

Symptom

When using the Object Container Data Source (OCDS) with the Entity Framework (EF) the updates are not performed properly when trying to attach the entity returned by the OCDS directly into the Entity Data Model (EDM).

Cause

Objects retrieved in the Updated event of the OCDS do not have the expected values in the Entity Framework’s properties (EntityKey and EntityState). This is because the OCDS creates a new instance of the object it contains/uses in each action performed, due to the stateless nature of web servers. The new instance that gets created in the new request contains only the values for the properties that are mapped in the controls that use the OCDS but it is not attached to the EDM.
EF&OCDS.png

Possible Usage Approach

A possible way to use OCDS with EF is attaching a handler to the Updated event fired by the OCDS and perform the following steps:
  1. Retrieve the entity from the EDM using its primary key (the object retrieved from the EDM has all the EF properties correctly loaded). It is important to focus in the fact that the GridView’s (or whatever DataBoundControl) DataKeyName property must be set to “EntityKey”, this allows the EntityKey property of the entity returned by the Updated event to be correctly set with the primary key.
  2. Update the retrieved entity with the values in the entity returned by the OCDS (you should only overwrite the values that are mapped in the GridView).
  3. Save the changes in the EDM.
Here’s an example about how you can implement it:
public void OnOCDSUpdated(Model.Entity1 updatedEntity)
{
      Model.EDM ent = new Model.EDM();
      
      //retrieve the entity from the EDM (by primary key)
      Model.Entity1 aux = ent.GetObjectByKey(updatedEntity.EntityKey) as Model.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();
} 

Last edited Oct 17, 2008 at 8:31 PM by dschenkelman, version 3

Comments

No comments yet.