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

时间:2018-12-21 13:54:51

标签: sql asp.net sql-server dapper

我有一个查询,该查询显示了我所有的船,但是我只想显示活动的船。

    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;

    }

我在表中有active和exclude属性,因此我尝试仅显示活动的船,但是通过此查询,它会不断返回船表中的所有记录,例如第一个

                  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 个答案:

答案 0 :(得分:1)

从括号中删除它:

@Entity class Parent{ @Id private Long id; @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST) private List<Child> children = new ArrayList<>(); } @Entity class Child{ @Id private Long id; @ManyToOne.. } public void testCascade(){ Parent parent = new Parent(); Child child1 = new Child(); Child child2 = new Child(); parent.addChild(child1); parent.addChild(child2); em.persist(parent); // works well until here Child child3 = new Child(); parent.addChild(child3); }