Updating the number of web page views in the database

I have a database table called Messages, which stores all the information about the presentation of an article on a website. There is a column called “Views”, which is a value that increases each time you view a specific message.

The process is as follows:

  • Get record from database
  • Increase current by one
  • Save the changes to the database.

Pretty simple. I am worried that if several people click the link at the same time, the updates will not be accurate. How do I approach this? Should this only be done in a 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);
    }
+3
source share
2 answers

:

UPDATE table SET views=views+1 WHERE myId=12;
+6

db _db, .

_db.ExecuteCommand("UPDATE posts SET views=views+1 WHERE id={0}", postId);

Gu .

http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx

+4

All Articles