1
使用Linq時我無法使用SQL全文搜索功能,因此我想在DbSet上使用SqlQuery方法,因爲我可以編寫原始SQL查詢。使用desider輸出運行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和我想有返回PagedList對象。實現它的最佳(好)方法是什麼?請注意,我希望我的數據庫能夠執行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);
}
那是穿越我的腦海裏。問題是所有匹配原始查詢的對象都必須從數據庫中加載到內存中。 – Dzenan