Database Reference
In-Depth Information
The Product entity describes products in your application. You want to throw an exception if an intermediate
update occurs between the time you retrieve a particular product entity and the time an update is performed in the
database. To implement that behavior, do the following:
1.
Add a column of type RowVersion to the table mapped to the Product entity.
2.
Right-click the design surface, and select Update Model from Database. Update the model
with the newly changed table. The updated model is shown in Figure 14-2 .
Figure 14-2. The updated model with the newly added TimeStamp property
3.
Right-click the TimeStamp property and select Properties. Change its Concurrency Mode
property to Fixed.
The code in Listing 14-1 demonstrates that changing the underlying row in the table between the time the product
entity is materialized and the time we update the table from changes in the product entity throws an exception.
Listing 14-1. Throwing an Exception If Optimistic Concurrency Is Violated
using (var context = new EF6RecipesContext())
{
context.Products.Add(new Product
{
Name = "High Country Backpacking Tent",
UnitPrice = 199.95M
});
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
// get the product
var product = context.Products.SingleOrDefault();
Console.WriteLine("{0} Unit Price: {1}", product.Name,
product.UnitPrice.ToString("C"));
// update out of band
context.Database.ExecuteSqlCommand(@"update chapter14.product set
unitprice = 229.95 where productId = @p0", product.ProductId);
 
Search WWH ::




Custom Search