首页 > 解决方案 > 如何通过单击按钮来增加数据库列中的值

问题描述

作为我正在进行的项目的一部分,用户可以创建一个帖子,然后其他用户可以点击“喜欢”或“不喜欢”按钮。

下面的代码是负责将表添加到数据库的 Post.cs 类。

public class Post
{
    //The post ID
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int postId { get; set; }
    // Foreign key to customer

    public string Id { get; set; }
    public string Email { get; set; }
    public string postTitle { get; set; }
    public string postBody { get; set; }
    public string postDepartment { get; set; }
    public string postCategory { get; set; }
    public bool postAnonymous { get; set; }
    public int postLikes { get; set; }
    public int postDislikes { get; set; }
    public DateTime postDate { get; set; }
}

以下代码是链接到任一按钮的后端 C# 代码。

protected void btnLike_Click(object sender, EventArgs e)
{

}

protected void btnDislike_Click(object sender, EventArgs e)
{

}

我试图让按钮在每次单击时将数据库上的整数值增加 +1,并且用户应该只能单击其中一个而不能多次喜欢//不喜欢。

我将如何尝试使用 asp.net 网络表单成功地做到这一点。

<-----------------编辑-------------------------->

protected void btnLike_Click(object sender, EventArgs e)
{
    var postIDforLike = // add logic to get the id of the post to increment the likes
    using (var _dbContext = new ApplicationDbContext()) 
    {
        var addLikeSql = "update post set postLikes = postLikes + 1 where postID = @id";
        var paramID = new SqlParameter("@id", postIDforLike);
        _dbContext.Database.ExecuteSqlCommand(addLikeSql, paramID);
    }
}

<--------------EDIT2---------- ->

<asp:Button ID="btnLike" class="btn btn-primary" runat="server" Text=" Like" Width="99.99px" OnClick="btnLike_Click" />&nbsp <asp:Button ID="btnDislike" Width="99.99px" class="btn btn-primary" runat="server" Text="Dislike " OnClick="btnDislike_Click"  />

        </div>
    <br />
         <%--------------------------------------
          Inserting Comment Information
          --------------------------------------%>
 <div class="col-md-12">
            <div class="panel panel-primary">
                  <div class="panel-heading">
    <h3 class="panel-title text-center">Add Comment</h3>
  </div>

  <div class="panel-body">


      <fieldset>
      <table class="nav-justified">
          <tr>
              <td class="modal-sm" style="width: 237px; height: 21px;">
      <label for="commentBody" class="col-lg-2 control-label">Comment:</label></td>
              <td style="width: 434px; height: 21px;">    
         <asp:TextBox Width="400px" style="resize:none;" class="form-control" ID="commentBody" runat="server" placeholder="Body" TextMode="MultiLine"></asp:TextBox>
              </td>
              <td style="height: 21px">    
                  <asp:RequiredFieldValidator controltovalidate="commentBody" ID="commentBodyValidator" runat="server" ErrorMessage="*Comment is required" ForeColor="Red"></asp:RequiredFieldValidator>    
              </td>
          </tr>
          </table>
      <br />
      <table class="nav-justified">
          <tr>
              <td style="height: 21px; width: 511px">    
      <label for="commentAnonymous" class="col-lg-2 control-label" style="left: 0px; top: 0px; width: 538px">Would you like this comment to be submitted anonymously?:</label></td>
              <td style="height: 21px; width: 104px">    
      <asp:RadioButtonList ID="commentAnonymous" runat="server" BorderStyle="None" CellPadding="0" CellSpacing="0">
        <asp:ListItem Value="1" Text="Yes">Yes</asp:ListItem>
        <asp:ListItem Value="0" Text="No">No</asp:ListItem>
    </asp:RadioButtonList>  
              </td>
              <td style="height: 21px"><asp:RequiredFieldValidator controltovalidate="commentAnonymous" ID="commentAnonymousValidator" runat="server" ErrorMessage="*Please select an option" ForeColor="Red"></asp:RequiredFieldValidator>    
              </td>
          </tr>
      </table>
      <br />
      <table class="nav-justified">
          <tr>
              <td class="modal-sm" style="width: 408px">&nbsp;</td>
              <td>
        <button type="reset" class="btn btn-default">Cancel</button>
          <asp:Button  class="btn btn-default" ID="commentSubmitBtn" runat="server" autopostback="false" onclick="AddComment" Text="Submit" />
              </td>
              <td>&nbsp;</td>
          </tr>
      </table>
          </fieldset>
                      <hr>

      <table class="display" id="commentsTable">
        <thead>
            <tr>
                <th>Comment</th>
                <th>User</th>
                <th>Date</th>

            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

标签: c#asp.netentity-framework

解决方案


我假设您使用实体框架(基于 post 类中使用的属性)。

最简单的方法是加载实体,增加值,然后调用 SaveChanges。但是,如果您不使用锁定机制,这是非常低效且危险的。

您可能正在寻找的是

update post set postLikes = postLikes + 1 where postID = @id

命令。这已经更有效了,因为您不会每次都在更新 Likes 值之前加载整个帖子。您可以使用上下文的 Database.ExecuteSqlCommand 执行这​​样的 Sql 命令。

另一种可能的解决方案是通过添加一个喜欢和不喜欢表来更改您的数据库模型,您可以在其中为每个喜欢/不喜欢添加一条记录。要获取当前的点赞数,您必须计算与帖子关联的记录数。这会增加开销,但优点是不会造成瓶颈,因为每次您想要更新类似字段时,数据库都必须锁定您的帖子记录。


推荐阅读