Databases Reference
In-Depth Information
Product product = context.Products.First(p => p.ProductName==”Mukuzani”);
product.Category = context.Categories.First(c => c.CategoryName==
”Beverages”);
context.SaveChanges();
In the next scenario, an existing Product entity is deleted, and its state changes from
Unchanged
to
Deleted
as soon as the
DeleteObject
method of the Products entity set is
called. At this point, the entity has been marked for deletion but not deleted yet in the
database. When the
SaveChanges
method of the context is called, the row storing the
entity is “physically” deleted from the Products table. The deleted Product entity is also
removed from the
ObjectContext
, and trying to get its
ObjectStateEntry
will result in an
InvalidOperationException
:
Product product = context.Products.First(p => p.ProductName == “Mukuzani”);
context.Products.DeleteObject(product);
context.SaveChanges();
Optimistic Concurrency Control
Most enterprise database applications require access by multiple simultaneous users. When
many people have access to the same data records, there is always a chance of two people
trying to modify the same record.
The following code illustrates this scenario by creating two different instances of the
NorthwindEntities
context, retrieving two different copies of the same Product entity,
making different changes to it and trying to save the changes. Obviously, you wouldn't
write code like this in a real-world application—
context1
and
context2
simply illustrate
the actions performed by two different users running your application on two different
computers:
using (NorthwindEntities context1 = new NorthwindEntities())
using (NorthwindEntities context2 = new NorthwindEntities())
{
Product product1 = context1.Products.First(p => p.ProductName == “Chai”);
Product product2 = context2.Products.First(p => p.ProductName == “Chai”);
product1.UnitsInStock = 50;
product2.UnitsInStock = 20;
context1.SaveChanges();
context2.SaveChanges();
}