Databases Reference
In-Depth Information
As you already know, in addition to its formidable querying capabilities, the Entity
Framework also helps you implement typical data access scenarios, such as creating a new
entity, finding an existing entity, and modifying or deleting it. To do this, the
ObjectContext
keeps track of all entities throughout their lifecycles—from creation to
modification to deletion.
Tracking Changes
When a new entity instance is added to an
ObjectContext
, the context records its state as
Added
. The following code shows how to examine entity state changes:
Product p = new Product() { ProductName = “Mukuzani” };
context.Products.AddObject(p);
Console.WriteLine(context.ObjectStateManager.GetObjectStateEntry(p).State);
context.SaveChanges();
Console.WriteLine(context.ObjectStateManager.GetObjectStateEntry(p).State);
The
ObjectStateManager
property of the
ObjectContext
class returns the actual object,
keeping track of all new entities that have been added to the context or existing entities
retrieved from the database. In this code, we use its
GetObjectStateEntry
method to
retrieve an
ObjectStateEntry
object that represents the newly added Product entity:
[Flags]
public enum EntityState
{
Detached = 1,
Unchanged = 2,
Added = 4,
Deleted = 8,
Modified = 16
}
The
State
property of the
ObjectStateEntry
returns an
EntityState
enumeration value,
which for newly created objects has the value
Added
until we call the
SaveChanges
method
of the
ObjectContext
, at which point the new entity is submitted to the database and the
entity state becomes
Unchanged
.
In the next example, when an existing Product entity is retrieved from the database, its
state is initially
Unchanged
. Then, as soon as the
Category
property is assigned, it becomes
Modified
. After the
SaveChanges
method is called and the changes are submitted to the
database, the entity state becomes
Unchanged
again: