Database Reference
In-Depth Information
14-4. Implementing the “Last Record Wins” Strategy
Problem
You want to make sure that changes to an object succeed regardless of any intermediate changes to the database.
Solution
Suppose you have a model like the one shown in Figure 14-5 .
Figure 14-5. Our model with the ForumPost entity
Our model represents posts by users of an Internet forum. Moderators of forums often want to review posts and
possibly change or delete them. The changes a moderator makes need to take precedence over any changes made by
the forum's users. In general, this can be implemented without much concern for concurrency, except when the user
makes a change between the time the moderator retrieves the post and the when the moderator calls SaveChanges()
to commit a change, such as a delete, to the database. In this case, we want the moderator's changes to overwrite the
user's changes. We want the moderator to win.
To implement this, follow the pattern shown in Listing 14-8. Be sure to set the Concurrency Mode on the
TimeStamp property to Fixed.
Listing 14-8. Implementing Last Record Wins
int postId = 0;
using (var context = new EF6RecipesContext())
{
// post is created
var post = new ForumPost { ForumUser = "FastEddie27", IsActive = false,
Post = "The moderator is a great guy." };
context.ForumPosts.Add(post);
context.SaveChanges();
postId = post.PostingId;
}
using (var context = new EF6RecipesContext())
{
// moderator gets post to review
var post = context.ForumPosts.First(p => p.PostingId == postId);
Console.WriteLine("Post by {0}: {1}", post.ForumUser, post.Post);
 
Search WWH ::




Custom Search