Reputation: 116100
I have a database table called "Posts" which stores all the information regarding an article submission on a website. There is a column named "Views" which is a value that gets incremented each time that particular post gets viewed.
The process is this:
Pretty straightforward. My concern is that if multiple people click the link at the same time, the updates wont be accurate. How should I approach this? Should this only be done ina stored procedure?
/// <summary>
/// Updates the view count of a post.
/// </summary>
/// <param name="postId">The Id of the post to update</param>
public bool UpdateViewCount(int postId)
{
Repository repository = new Repository();
Post p = repository.Posts.Where(p => p.Id == postId).SingleOrDefault();
if (p != null)
{
p.Views++;
}
repository.SubmitChanges(System.Data.Linq.ConflictMode.ContinueOnConflict);
}
Upvotes: 3
Views: 492
Reputation: 15987
If your db context is called _db you can use this.
_db.ExecuteCommand("UPDATE posts SET views=views+1 WHERE id={0}", postId);
for further reading check out the Gu's post here.
Upvotes: 4
Reputation: 13536
Do it in one go:
UPDATE table SET views=views+1 WHERE myId=12;
Upvotes: 6