Database Reference
In-Depth Information
// poster changes post out-of-band
Context.Database.ExecuteSqlCommand(@"update chapter14.forumpost
set post='The moderator''s mom dresses him funny.'
where postingId = @p0", new object[] { postId.ToString() });
Console.WriteLine("Fast Eddie changes the post");
// moderator doesn't trust Fast Eddie
if (string.Compare(post.ForumUser, "FastEddie27") == 0)
post.IsActive = false;
else
post.IsActive = true;
try
{
// refresh any changes to the TimeStamp
var postEntry = context.Entry(post);
postEntry.OriginalValues.SetValues(postEntry.GetDatabaseValues());
context.SaveChanges();
Console.WriteLine("No concurrency exception.");
}
catch (DbUpdateConcurrencyException exFirst)
{
try
{
// try one more time.
var postEntry = context.Entry(post);
postEntry.OriginalValues.SetValues(postEntry.GetDatabaseValues());
context.SaveChanges();
}
catch (DbUpdateConcurrencyException exSecond)
{
// we tried twice...do something else
}
}
}
The following is the output of the code in Listing 14-8:
Post by FastEddie27: The moderator is a great guy.
Fast Eddie changes the post
No concurrency exception.
How It Works
The TimeStamp property is marked for concurrency because its ConcurrencyMode is set to Fixed. As part of the
update statement, the value of the TimeStamp property is checked against the value in the database. If they differ,
Entity Framework will throw a DbUpdateConcurrencyException . We've seen this behavior in the previous recipes in
this chapter. What's different here is that we want the change from the client, in this case the moderator, to overwrite
the newer row in the database. We do this by repeating a particular strategy; however, even using this strategy,
it's possible that we will not be able to update our data successfully.
 
Search WWH ::




Custom Search