Database Reference
In-Depth Information
using (var context = new EF6RecipesContext())
{
// get the account
var account = context.Accounts.First(a => a.AccountNumber == "8675309");
Console.WriteLine("Account for {0}", account.Name);
Console.WriteLine("\tPrevious Balance: {0}", account.Balance.ToString("C"));
// some other process updates the balance
Console.WriteLine("[Rogue process updates balance!]");
context.Database.ExecuteSqlCommand(@"update chapter14.account set balance = 1000
where accountnumber = '8675309'");
// update the account balance
account.Balance = 10M;
try
{
Console.WriteLine("\tNew Balance: {0}", account.Balance.ToString("C"));
context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
}
The following is the output of the code in Listing 14-10:
Account for Robin Rosen
Previous Balance: $100.00
[Rogue process updates balance!]
New Balance: $10.00
Exception: Store update, insert, or delete statement affected an unexpected number of rows (0).
Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager
entries.
How It Works
The code in Listing 14-10 demonstrates using the stored procedures we've mapped to the insert, update, and delete
actions. In the code, we purposely introduce an intervening update between the retrieval of an account object and
saving the account object to the database. This rogue update causes the TimeStamp value to be changed in the
database after we've materialized the object in the DbContext. This concurrency violation is detected by Entity
Framework because the number of rows affected by the UpdateAccount() procedure is zero.
The mappings shown in Figure 14-7 tell Entity Framework how to keep the TimeStamp property correctly
synchronized with the database and how to be informed of the number of rows affected by the insert, update, or
delete actions. The Result Column for the insert and the update actions is mapped to the TimeStamp property on
the entity. For the update action, we need to make sure that Entity Framework uses the original value from the entity
when it constructs the statement invoking the UpdateAccount() procedure. These two settings keep the TimeStamp
property synchronized with the database. Because our stored procedures return the number of rows affected by their
respective updates in an output parameter, we need to check the Rows Affected Parameter box for this parameter for
each of the action mappings.
 
 
Search WWH ::




Custom Search