Using the Entity Framework: Update Operation (Quick Reference)

How to Use the Entity Framework to Update Records in a Relational Database

This quick reference is for those who are using the Entity Framework and want examples of how to perform everyday CRUD tasks. We’ll take a look at how to update objects and associated objects using the Entity Framework.

Quick Reference Setup

Entity Framework & Linq to Entities: “Movies” Example Setup contains diagrams representing the database structure, entity data model, and entity object model used in the following code examples.

Update a Director object using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = _entities.DirectorSet.
               Where(d => d.Name == "Spike Jonze").First();

     spikeJonze.Name = "Adam Spiegel a.k.a \"Spike Jonze\"";
     _entities.SaveChanges();

     Console.ReadLine();
}

First, we retrieve a Director object by specifying a value for the Name property in a lambda expression. Next, we update the Director’s Name property. Finally, we call the ObjectContext’s SaveChanges method to commit the changes to the model and the database.

Using the ObjectStateManager when Updating a Director object using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = _entities.DirectorSet.
               Where(d => d.Name == "Spike Jonze").First();

     spikeJonze.Name = "Adam Spiegel a.k.a \"Spike Jonze\"";

     ObjectStateEntry entry = _entities.ObjectStateManager.
               GetObjectStateEntry(spikeJonze.EntityKey);
     IEnumerable<string$gt; modProps = entry.
               GetModifiedProperties();

     foreach (string prop in modProps)
     {
          Console.WriteLine("Modified Property: {0}", 
                    prop.ToString());

          Console.WriteLine("IsDbNull: {0}", 
                    entry.OriginalValues.
                    IsDBNull(
                         entry.OriginalValues.GetOrdinal(prop)
                    )
          );

          Console.WriteLine("Changed from: {0}", 
                    entry.OriginalValues[prop]);

          Console.WriteLine("Changed to: {0}", 
                    entry.CurrentValues[prop]);
     }

     Console.WriteLine("Entity State: {0}", entry.State);

     Console.WriteLine("\n--> All Original Values");
     for (int i = 0; i < entry.OriginalValues.FieldCount; i++)
     {
          Console.WriteLine("{0}: {1}", 
                    entry.OriginalValues.GetName(i), 
                    entry.OriginalValues[i]);
     }

     _entities.SaveChanges();

     Console.ReadLine();
}

After modifying a property an object, we can use the ObjectStateManager to access state information such as, which properties were modified, those properties original values, their current values, and other helpful information.

To access this information we call the ObjectContext’s GetObjectStateEntry method passing in the Director’s EntityKey. This method returns the ObjectStateEntry for the specified Director object. To determine which properties have been modified, we call the ObjectStateEntries GetModifiedProperties method which returns a collection of the names of any properties whose current values are different from their original values.

To determine the original value of a property, we retrieve the value at a given index in the ObjectStateEntry’s OriginalValues collection. Since OriginalValues is an indexed collection we can specify either the number of the database column or the name of the column (or property) as such, entry.OriginalValues["name"]. We then use the CurrentValues collection to retrieve the current value of the modified property.

Lastly, for the purpose of illustration, we loop over the OriginalValues collection and output all of the Director object’s property names and their respective values.

Here is the output:

Modified Property: Name
IsDbNull: False
Changed from: Spike Jonze
Changed to: Adam Spiegel a.k.a "Spike Jonze"
Entity State: Modified

--> All Original Values
ID: 33
Name: Spike Jonze
Hometown: Rockville Maryland
Birthday: 10/22/1969
Advertisements

One Response

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: