Dapper 查询,结合属性与分页一起使用

Posted

技术标签:

【中文标题】Dapper 查询,结合属性与分页一起使用【英文标题】:Dapper query, combining attributes to use with pagination 【发布时间】:2018-12-21 13:54:50 【问题描述】:

我有显示我所有船只的查询,但我只想显示活动船只。

    public Pagination<Boats> GetAll(string name , int pageSize, int pageNumber)
    
        var cn = Db.Database.Connection;

        var sql = @"SELECT * FROM Boats" +
                  "WHERE (@Name IS NULL OR Name LIKE @Name + '%')" +
                  "ORDER BY [Name ] " +
                  "OFFSET " + pageSize * (pageNumber - 1) + " ROWS " +
                  "FETCH NEXT " + pageSize + " ROWS ONLY " +
                  " " +
                  "SELECT COUNT(Id) FROM Boats" +
                  "WHERE (@Name IS NULL OR Name LIKE @Name + '%')";

        var multi = cn.QueryMultiple(sql, new  Name = name );
        var boats= multi.Read<Boats >();
        var total = multi.Read<int>().FirstOrDefault();

        var paginationList= new Pagination<Boats>()
        
            List = boats,
            Count = total
        ;

        return paginationList;

    

我在表中有活动和排除属性,所以我试图只显示活动的船,但是通过这个查询,它不断返回船表中的所有记录,比如第一个

                  var sql = @"SELECT * FROM Boats " +
                  "WHERE (@Name IS NULL OR Name LIKE @Name + '%' AND  Active=1 AND Excluded=0)" +
                  "ORDER BY [Name] " +
                  "OFFSET " + pageSize * (pageNumber - 1) + " ROWS " +
                  "FETCH NEXT " + pageSize + " ROWS ONLY " +
                  " " +
                  "SELECT COUNT(Id) FROM Boats " +
                  "WHERE (@Name IS NULL OR Name LIKE @Name + '%' AND  Active=1 AND Excluded=0)";

任何想法如何将 Name 属性与 Active 和 Excluded 属性结合起来?

【问题讨论】:

【参考方案1】:

从括号中删除:

"WHERE (@Name IS NULL OR Name LIKE @Name + '%') AND Active=1 AND Excluded=0"

【讨论】:

以上是关于Dapper 查询,结合属性与分页一起使用的主要内容,如果未能解决你的问题,请参考以下文章

Linq组合查询与分页组合查询结合

是否可以将FirestorRecyclerAdaper与分页结合起来?

Mysql 排序Order by与分页limit结合的数据异常问题

Node.js学习14~实现翻页或分页查询

使用PageHelper插件分页结合mybatis返回的列表个数不对问题解决

使用SqlSugar结合MySql开发