Wednesday, May 28, 2008

ADO.NET Entity Framework - Part 3

ADO.NET Entity framework - update changes to the storage layer.

ADO.NET Entity framework helps you in creating, updating and deleting objects by using Object Services. Object Services keep track of the changes and then update them to the persisted storage by executing the corresponding T-SQL statements. The SaveChanges() method of the ObjectContext class is used for saving the changes to the persistence storage.

In this post I will explain how to apply changes on a detached object to the storage layer.

When a query is executed within an object context, the returned objects are automatically attached to the context. Object Services also lets you attach existing objects to an object context. Once you attach an object to the context. You can use the SaveChanges() method to update the changes in the database.

The ApplyPropertyChanges method can be used when the object already exists in the store and the detached object has property updates that you want to persist.

In the following example an updated Customer object is passed to the Save method. The Save method retrieves the original object by using the EntityKey and then updates the original object by the ApplyPropertyChanges() method. Later the changes are updated by using the SaveChanges() method of the ObjectContext class.

public int Save(Customer myCustomer)

{

EntityKey key;

object originalItem;

using (TwoWayDataBindingEntities entites = new TwoWayDataBindingEntities())

{

try

{

// Get the detached object's entity key.

if (myCustomer.EntityKey == null)

{

// Get the entity key of the updated object.

key = entites.GetEntityKey("Customers", myCustomer);

}

else

{

key = myCustomer.EntityKey;

}

// Get the original item based on the entity key from the context

// or from the database.

if (entites.TryGetObjectByKey(key, out originalItem))

{

// Call the ApplyPropertyChanges method to apply changes

// from the updated item to the original version.

entites.ApplyPropertyChanges(key.EntitySetName, myCustomer);

}

return entites.SaveChanges();

}

catch (InvalidOperationException ex)

{

//Exception handling logic

}

return 0;

}

}

1 comment:

Anonymous said...

tks for this. I'm searching for this for days.
tks
tks
tks