gpt4 book ai didi

asp.net-mvc - 使用 Telerik MVC Extensions Grid 在数据库服务器上进行分页

转载 作者:行者123 更新时间:2023-12-04 06:10:52 24 4
gpt4 key购买 nike

Telerik mention此功能:

Linq based expression engine for pushing grid operations (paging, sorting, filtering and grouping) to the database server



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

最佳答案

这在一定程度上取决于您如何将数据发送到 View 。如果将 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 绑定(bind)...
// 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 进行,但当需要实际迭代集合时,具体类型(上面示例中的 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 });

关于asp.net-mvc - 使用 Telerik MVC Extensions Grid 在数据库服务器上进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7793969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com