【问题标题】:How to increment a value within a database column by button click如何通过单击按钮来增加数据库列中的值
【发布时间】:2019-08-21 21:44:16
【问题描述】:

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

下面的代码是负责将表添加到数据库的 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);
    }
}

<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.net entity-framework


    【解决方案1】:

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

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

    你可能正在寻找的是一个

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

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

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

    【讨论】:

    • 是的,我正在使用实体框架,很抱歉没有在我原来的问题中说明这一点。我可能更愿意将它保留在帖子表中,而不是制作一个新表,因为这对我来说更有意义。但是我不明白我会发布您建议的更新后声明吗?即使这对我来说确实有意义
    • 你可以在这里找到如何执行一条sql语句的解释:learnentityframeworkcore.com/raw-sql#database.executesqlcommand
    • 我浏览了那个例子,只有 1 行我没有得到,那就是“ var name = new SqlParameter("@CategoryName", "Test"); ”之一。我已经用我添加的新代码编辑了我的问题,你能检查它看起来是否正确吗?
    • 我修改了您的编辑以修复您遇到问题的行。需要新的SqlParameter来设置Sql中@id参数的Parameter Value的值。
    • 完美!这解决了验证问题,其余代码都是正确的! :D 喜欢和不喜欢都正常工作 :D 非常感谢你回答我所有的问题并与我裸露:)
    【解决方案2】:

    //你需要有一个新的表来处理类似用户的帖子 // 具有 UserId int PostId int Like 或 dislike 的 UserLike 表,因此您不需要实体上的 Likes 和 Dislikes 属性! //假设,这个操作可以由用户登录完成。

    protected void btnLike_Click(object sender, EventArgs e)
            {
    //you need to get postId while button clicked... 
                DBContext db = new DbContext();
                var user = Session["loggedUser"] as User ;
                var didUserLike = db.Post.Where(p=>p.PostId == postId).Select(x=>x.UserId == user.UserId).FirstOrDefault());
    if(didUserLike.Count() > 0){
    
    //Operation like enable button disable button!
    }   //and if you want to do it for dislike..yes you can
            }
    

    对不起,我这里没有工作室或代码,我无法控制它。但我认为你了解结构。祝你有美好的一天。

    已编辑(添加):

    并且鉴于您不需要从您的 enetiyt 的属性中显示,因为这可以通过查询来计算。这不适合数据库设计。

    你可以这样做;

      public int likeCountForPost(int id){
          var postLikes = db.PostLikes.Where(x=>x.PostId == id && x.PostLike==1).Count();
          return  postLikes;
    }
    

    您也可以通过将不喜欢的返回计数仅更改为 1 到 2 来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 2014-12-09
      • 2014-09-20
      相关资源
      最近更新 更多