Changing and Updating ADO.NET Entities


One last matter to consider is updating entities and persisting their state back to the physical data layer. ADO.NET Entity Framework transparently monitors object state and instancing whenever we change an object’s contents, leveraging the base class Entity from which every single entity type inherits. Let’s start with Listing A-17, which provides an example of how to modify an entity instance.

Listing A-17: Entity modification and data persistence

image from book
  using (NorthwindEntities db = new NorthwindEntities()) {     var customer = (from   c in db.Customers                     where  c.CustomerID == "ALFKI"                     select c).AsEnumerable().First();     Console.WriteLine("Customer ContactName: {0}", customer.ContactName);     Console.WriteLine("Customer state: {0}", customer.EntityState);     customer.ContactName = "Maria Anders - Changed";     Console.WriteLine("Customer ContactName: {0}", customer.ContactName);     Console.WriteLine("Customer state: {0}", customer.EntityState);     db.SaveChanges();     Console.WriteLine("Customer state: {0}", customer.EntityState); } 
image from book

The output of this code is like the following:

 Customer ContactName: Maria Anders Customer state: Unchanged Customer ContactName: Maria Anders - Changed Customer state: Modified Customer state: Unchanged

You can see that as soon as we change the customer instance, we implicitly also change its EntityState value, which keeps track of the entity status throughout its lifetime. This property can assume the classical values of Added, Deleted, Detached, Modified, and Unchanged. The entity status is tracked by the ObjectContext engine. In fact, we are working inside a using block applied to a NorthwindEntities object, and every query is executed against the current context. Whenever a user queries for an entity instance, the ObjectContext base engine checks to determine whether the object has already been loaded into memory. If the object is already available, the engine returns that instance; otherwise, it retrieves the instance from the physical database and keeps track of it. Whenever a piece of code changes the object instance, the ObjectContext is notified and tracks the information. In Listing A-18, you can see the instancing and object concurrency policy in action.

Listing A-18: Entity status and concurrency

image from book
  using (NorthwindEntities db = new NorthwindEntities()) {     var customer1 = (from   c in db.Customers                      where  c.CustomerID == "ALFKI"                      select c).AsEnumerable().First();     Console.WriteLine("Customer 1 ContactName: {0}", customer1.ContactName);     Console.WriteLine("Customer 1 state: {0}", customer1.EntityState);     customer1.ContactName = "Maria Andersa - Changed";     Console.WriteLine("Customer 1 ContactName: {0}", customer1.ContactName);     Console.WriteLine("Customer 1 state: {0}", customer1.EntityState);     var customer2 = (from   c in db.Customers                      where  c.CustomerID == "ALFKI"                      select c).AsEnumerable().First();     Console.WriteLine("Customer 2 ContactName: {0}", customer2.ContactName);     Console.WriteLine("Customer 2 state: {0}", customer2.EntityState);     db.SaveChanges();     Console.WriteLine("Customer 1 state: {0}", customer1.EntityState);     Console.WriteLine("Customer 2 state: {0}", customer2.EntityState);     Console.WriteLine("Customer 1 HashCode: {0}", customer1.GetHashCode());     Console.WriteLine("Customer 2 HashCode: {0}", customer2.GetHashCode());     Console.WriteLine("Customer 1 Equals Customer 2? {0}",         customer1.Equals(customer2)); } 
image from book

The result of the previous code excerpt is the following:

 Customer 1 ContactName: Maria Anders Customer 1 state: Unchanged Customer 1 ContactName: Maria Anders - Changed Customer 1 state: Modified Customer 2 ContactName: Maria Anders - Changed Customer 2 state: Modified Customer 1 state: Unchanged Customer 2 state: Unchanged Customer 1 HashCode: 7765704 Customer 2 HashCode: 7765704 Customer 1 Equals Customer 2? True 

The object instances that hold customer1 and customer2 are exactly the same. They have the same HashCode, and Equals returns true. Perhaps you are wondering how ObjectContext identifies object instances. It uses the key of the entity; therefore, it is very important to correctly define unique keys within the CSDL.

Every time you need to change an entity, you can simply update its properties or invoke its methods. Under the cover, the ADO.NET Entity Framework engine guarantees that you do not have multiple instances of the same entity-thereby helping you to avoid concurrency issues within your own application. It does this by validating input against the EDM you defined and keeping track of every kind of change you make over entity instances. Changes are made in memory, and none of them are directly persisted to the physical storage until you invoke the SaveChanges method of the ObjectContext instance. Only when you invoke this method is the data sent to the database.

Your actions could be concurrent with those of other users or applications. ObjectContext prevents your code from being concurrent, but someone else could change an entity on the persistence layer that you have changed in memory. In this situation, an OptimisticConcurrencyException is thrown.

Whenever you need to perform transactional activities, you can use either a TransactionScope or an old-style explicit DbTransaction object. We suggest that you adopt the new transactional framework of .NET Framework 2.0 (System.Transactions), but providing a transaction management explanation is not a goal of this book. Simply consider the example in Listing A-19, in which we use TransactionScope to cover the result of an entity modification sentence.

Listing A-19: Entity modification using TransactionScope

image from book
  using (NorthwindEntities db = new NorthwindEntities()) {     using (TransactionScope scope = new TransactionScope()) {         var customer = (from c in db.Customers                         where c.CustomerID == "ALFKI"                         select c).AsEnumerable().First();         customer.ContactName = "Paolo Pialorsi";         db.SaveChanges();         scope.Complete();     } } 
image from book




Introducing Microsoft LINQ
Introducing MicrosoftВ® LINQ
ISBN: 0735623910
EAN: 2147483647
Year: 2007
Pages: 78

Similar book on Amazon
Programming Microsoftu00ae LINQ (PRO-Developer)
Programming Microsoftu00ae LINQ (PRO-Developer)
Programming Microsoft LINQ in Microsoft .NET Framework 4
Programming Microsoft LINQ in Microsoft .NET Framework 4
Pro LINQ in VB8: Language Integrated Query in VB 2008 (Expert's Voice in .NET)
Pro LINQ in VB8: Language Integrated Query in VB 2008 (Expert's Voice in .NET)
Pro LINQ Object Relational Mapping in C# 2008 (Expert's Voice in .NET)
Pro LINQ Object Relational Mapping in C# 2008 (Expert's Voice in .NET)

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net