【问题标题】:Updating the view count of a webpage in a database更新数据库中网页的查看次数
【发布时间】:2008-12-18 00:04:24
【问题描述】:

我有一个名为“Posts”的数据库表,它存储有关网站上文章提交的所有信息。有一个名为“Views”的列,每次查看特定帖子时都会增加一个值。

流程是这样的:

  1. 从数据库中获取记录
  2. 电流加一
  3. 将更改保存到数据库。

非常简单。我担心的是,如果多个人同时单击该链接,则更新将不准确。我应该如何处理这个?这应该只在存储过程中完成吗?

    /// <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);
    }

【问题讨论】:

    标签: c# .net asp.net asp.net-mvc


    【解决方案1】:

    一口气完成:

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

    【讨论】:

      【解决方案2】:

      如果您的 db 上下文称为 _db,您可以使用它。

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

      如需进一步阅读,请在此处查看顾的帖子。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多