2011-10-17 69 views
1

Telerik的mention此功能的数据库服务器上:寻呼与Telerik的MVC扩展网格

用于推动网格运算(寻呼,排序,过滤和分组)到数据库服务器

LINQ的基于表达式引擎

但是如何启用它?这些例子都是IEnumerable的东西或其他。

回答

2

这取决于你如何将数据发送到视图。如果将linq查询留作懒惰评估,那么分页将发生在数据库上。但是,如果在数据层中执行了ToList()或其他枚举操作,那么您将错过了所有数据,并且必须设置一些内容来手动分页。

为了更好的展现...

// In your initial page load 
public ActionResult Index() 
{ 
    return View(new MyViewModel 
    { 
     // ... other view data 

     // set order or .Where for initial load, but don't use .ToList or enumerate 
     MyObjects = _db.MyObjects.OrderBy(m => m.Name) 
     // When this is passed into the grid, it will finalize the paging there 
     // and when the grid enumerates MyObjects, it will only pull the relevant 
     // items from the database. 
    }); 
} 

如果您正在使用AJAX结合...

// In an ajax grid responder action 
[GridAction] 
public ActionResult AjaxGridAction() 
{ 
    // Assuming _db is a CodeFirst DbContext, GridModel will handle filtering, 
    // paging, and sorting in the database as linq applies those methods to the 
    // IQueryable _db.MyObjects 
    return View(new GridModel(_db.MyObjects)); 
} 

如果您使用的是存储库模式(虽然的DbContext已经是一个真正的资源库) ,然后让它返回懒惰的对象:

public IEnumerable<T> GetMyObjects() 
{ 
    // Don't use ToList or enumerate them in your repository - that will 
    // pull all the data before the Telerik grid has filtered it. 
    return _db.MyObjects; 
} 

即使所有东西都绕过IEnumerable,wh现在是时候实际遍历集合,具体类型(上例中的DbSet)将成为实际处理该集合的方式。

如果您使用的是类似于AutoMapper的东西,请注意,在映射过程中意外拉出所有记录非常容易。 AutoMapper 2有一个解决方案,用于投影数据库而无需迭代,但目前还没有文档。我一直在使用this solution for that,直到有时间调查AutoMapper 2为止。

_db.MyObjects.Project().To<MyObjectsViewModel>(); 

基本上包自动项目性质的,而不是做这样的:

_db.MyObjects 
    .Select(o => new MyObjectsViewModel { // manually map properties, ewww }); 
+0

谢谢你,所以我想,他们检查了IEnumerable是否是IQueryable的被窝里。解释它。干杯,皮特。 – 2011-10-18 08:25:03

0

对于服务器分页/排序,您应该设置GridOperationMode.Server道具。

有使用的一个样本:

Html.Telerik().Grid<PartnerUserViewModel>() 
    .Name("Grid").DataBinding(binding => binding.Ajax().OperationMode(GridOperationMode.Server).Select("GetUsers", "Partner")).Columns(columns => 
    { 
     columns.Bound(o => o.Representer).Title("Representer"); 
    });   
    .Sortable(sorting => sorting.OrderBy(sortOrder => sortOrder.Add(p => p.DateCreated).Descending())) 
    .Filterable() 
    .Pageable(pager => pager.Position(GridPagerPosition.Both).PageSize(5)) 
    .Groupable()