C# 使用PetaPoco分页映射关系

C# 使用PetaPoco分页映射关系,c#,sql-server,petapoco,C#,Sql Server,Petapoco,我使用的是PetapocoV5.1.228.0,我试图通过分页(每页30个项目)获取人员列表以及他们所属的类别 这是我的代码: IEnumerable<Person> people; var sql = new Sql("SELECT * FROM Person p INNER JOIN Category c ON p.CategoryId = c.Id"); using (var db = GetDatabaseConnection()) { var paging = db

我使用的是PetapocoV5.1.228.0,我试图通过分页(每页30个项目)获取人员列表以及他们所属的类别

这是我的代码:

IEnumerable<Person> people;
var sql = new Sql("SELECT * FROM Person p INNER JOIN Category c ON p.CategoryId = c.Id");

using (var db = GetDatabaseConnection()) {
   var paging = db.Page<Person>(currentPage, 30, sql);
   people = paging.Items;
}
Category.cs

public class Person {
   public int Id { get; set; }
   public string Name { get; set; }
   public int CategoryId { get; set; }
   public Category Category { get; set; }
}
public class Category {
   public int Id { get; set; }
   public string Name { get; set; }
}
问题是它不会填充Person对象中的Category属性。据我所知,只有
db.Fetch
允许指定多种类型,但在这种情况下,我需要自己编写分页功能的代码


最好的方法是什么?

您可以在IDatabase上使用扩展方法:

public static Page<TRet> PagedFetch<T1, T2, TRet>(this PetaPoco.IDatabase db, long page, long itemsPerPage, Func<T1, T2, TRet> cb, string sql, params object[] args)
        {
            SQLParts parts;
            if (!db.Provider.PagingUtility.SplitSQL(sql, out parts))
                throw new Exception("Unable to parse SQL statement for paged query");

            db.Provider.BuildPageQuery((page - 1) * itemsPerPage, itemsPerPage, parts, ref args);

            sql = string.Format("{0} offset {1} rows fetch next {2} rows only", sql, (page - 1) * itemsPerPage, itemsPerPage);

            var data = db.Fetch(cb, sql, args);

            var result = new Page<TRet>
            {
                Items = data,
                TotalItems = db.ExecuteScalar<long>(parts.SqlCount),
                CurrentPage = page,
                ItemsPerPage = itemsPerPage
            };

            result.TotalPages = result.TotalItems / itemsPerPage;

            if ((result.TotalItems % itemsPerPage) != 0)
                result.TotalPages++;

            return result;
        }
public static Page PagedFetch(此PetaPoco.IDatabase数据库、长页面、长项目页面、Func cb、字符串sql、参数对象[]args)
{
零件;
if(!db.Provider.pagingulity.SplitSQL(sql,out parts))
抛出新异常(“无法分析分页查询的SQL语句”);
db.Provider.BuildPageQuery((第-1页)*itemsPerPage、itemsPerPage、parts、ref参数);
sql=string.Format(“{0}偏移量{1}行仅获取下一个{2}行”,sql,(第1页)*itemsPerPage,itemsPerPage);
var data=db.Fetch(cb、sql、args);
var result=新页面
{
项目=数据,
TotalItems=db.ExecuteScalar(parts.SqlCount),
CurrentPage=第页,
ItemsPerPage=ItemsPerPage
};
result.TotalPages=result.TotalItems/itemsPerPage;
如果((result.TotalItems%itemsPerPage)!=0)
结果:TotalPages++;
返回结果;
}