Mapping relationships using PetaPoco paging

£可爱£侵袭症+ 提交于 2020-01-12 09:15:26

问题


I am using PetaPoco v5.1.228.0 and I am trying to fetch a list of people along with the category they belong to, using paging (30 items per page).

This is my code:

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;
}

Person.cs

public class Person {
   public int Id { get; set; }
   public string Name { get; set; }
   public int CategoryId { get; set; }
   public Category Category { get; set; }
}

Category.cs

public class Category {
   public int Id { get; set; }
   public string Name { get; set; }
}

The problem is it won't populate the Category property within the Person object. As far as I know only db.Fetch allows multiple types to be specified, but in this case I would need to code the paging functionality myself.

What would be the best way to do it?


回答1:


You can do it with an extention metod over 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;
        }


来源:https://stackoverflow.com/questions/40395854/mapping-relationships-using-petapoco-paging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!