使用 Linq 时,我无法使用 SQL 全文搜索功能,因此我想在 DbSet 上使用 SqlQuery 方法,它允许我编写原始 SQL 查询。
让我们考虑以下代码:
IQueryable<Message> query = DBContext.Set<Message>();
PagedList<Message> messages = query.Where(x => x.Content.Contains("magic"))
.OrderBy(x => x.CreatedDate)
.ToPagedList<Message>(50, 2);
如果我想运行以下 SqlQuery 查询:
DBContext.Set<Message>().SqlQuery("SELECT * FROM Message WHERE CONTAINS("Content", 'magic')");
SqlQuery 方法返回IEnumerable<Message>
,我想PagedList<Message>
返回对象。实现它的最佳(好)方法是什么?请注意,我希望我的数据库执行 SQL 查询,而不是在内存中进行过滤。
PagedList 实现
public class PagedList<T> : List<T>, IPagedList
{
public PagedList()
{
this.TotalCount = 0;
this.PageSize = 0;
this.PageIndex = 0;
this.TotalPages = 0;
this.CurrentPage = 0;
}
public PagedList(IQueryable<T> source, int pageIndex, int pageSize)
{
this.TotalCount = source.Count();
this.PageSize = pageSize;
this.PageIndex = pageIndex;
this.TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);
this.CurrentPage = Math.Max(1, pageIndex);
this.AddRange(source.Skip((this.CurrentPage - 1) * pageSize).Take(pageSize).ToList());
}
public PagedList(List<T> source, int index, int pageSize)
{
this.TotalCount = source.Count();
this.PageSize = pageSize;
this.PageIndex = index;
this.TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);
this.CurrentPage = Math.Max(1, index);
this.AddRange(source.Skip(index * pageSize).Take(pageSize).ToList());
}
public int TotalCount { get; set; }
public int TotalPages { get; set; }
public int PageSize { get; set; }
public int PageIndex { get; set; }
public int CurrentPage { get; set; }
}
分页列表扩展方法:
public static PagedList<T> ToPagedList<T>(this IQueryable<T> query, int pageIndex, int pageSize) where T : class
{
return new PagedList<T>(query, pageIndex, pageSize);
}