Database Reference
In-Depth Information
var agent2 = context.Agents.Single(a => a.Name == "Phillip Marlowe");
agent1.Phone = "817 353-4458";
context.SaveChanges();
// update the other agent's number out-of-band
context.Database.ExecuteSqlCommand(@"update Chapter14.agent
set Phone = '817 294-6059' where name = 'Phillip Marlowe'");
// now change it using the model
agent2.Phone = "817 906-2212";
try
{
context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
Console.WriteLine("Exception caught updating phone number: {0}",
ex.Message);
}
}
using (var context = new EF6RecipesContext())
{
Console.WriteLine("-- All Agents --");
foreach (var agent in context.Agents)
{
Console.WriteLine("Agent: {0}, Phone: {1}", agent.Name, agent.Phone);
}
}
The following is the output of the code in Listing 14-6. Notice that we caught the exception thrown during
SaveChanges() and printed the exception message:
Exception caught updating phone number: 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.
-- All Agents --
Agent: Janet Rooney, Phone: 817 353-4458
Agent: Phillip Marlowe, Phone: 817 294-6059
How It Works
The key to leveraging the concurrency infrastructure in Entity Framework is in the implementation of the stored
procedures (see Listing 14-4) and in how we mapped the input parameters and the result values. Let's look at each
stored procedure.
The InsertAgent() procedure takes in the name and phone number for the agent and executes an insert
statement. This results in the database computing a timestamp value that is inserted into the table along with the
name and phone number. The select statement retrieves this newly generated timestamp. After the insert, the entity
 
Search WWH ::




Custom Search