服务器端分页,排序和过滤性能

时间:2018-10-21 17:56:09

标签: c# jquery asp.net-mvc entity-framework datatables

我在数据库中只有一个表,具有200万条记录,我希望用户能够浏览数据,并且能够对数据进行排序和过滤。 用户也应该能够在页面之间导航

这是我的MVC控制器

 public class AssetController : Controller
    {

        private ApplicationDbContext _dbContext;

        public ApplicationDbContext DbContext
        {
            get
            {
                return _dbContext ?? HttpContext.GetOwinContext().Get<ApplicationDbContext>();
            }
            private set
            {
                _dbContext = value;
            }

        }

        public AssetController()
        {

        }

        public AssetController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        // GET: Asset
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Get([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel)
        {
            IEnumerable<Asset> query = DbContext.Assets;
            var totalCount = query.Count();

            #region Filtering
            // Apply filters for searching
            if (requestModel.Search.Value != string.Empty)
            {
                var value = requestModel.Search.Value.Trim();
                query = query.Where(p => p.Barcode.Contains(value) ||
                                         p.Manufacturer.Contains(value) ||
                                         p.ModelNumber.Contains(value) ||
                                         p.Building.Contains(value)
                                   );
            }

            var filteredCount = query.Count();

            #endregion Filtering

            #region Sorting
            // Sorting
            var sortedColumns = requestModel.Columns.GetSortedColumns();
            var orderByString = String.Empty;

            foreach (var column in sortedColumns)
            {
                orderByString += orderByString != String.Empty ? "," : "";
                orderByString += (column.Data) + (column.SortDirection == Column.OrderDirection.Ascendant ? " asc" : " desc");
            }

            query = query.OrderBy(orderByString == string.Empty ? "BarCode asc" : orderByString);

            #endregion Sorting

            // Paging
            query = query.Skip(requestModel.Start).Take(requestModel.Length);


            var data = query.Select(asset => new
            {
                AssetID = asset.AssetID,
                BarCode = asset.Barcode,
                Manufacturer = asset.Manufacturer,
                ModelNumber = asset.ModelNumber,
                Building = asset.Building,
                RoomNo = asset.RoomNo,
                Quantity = asset.Quantity
            }).ToList();

            return Json(new DataTablesResponse(requestModel.Draw, data, filteredCount, totalCount), JsonRequestBehavior.AllowGet);
        }

    }

和下面是index.cshtml

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-primary list-panel" id="list-panel">
            <div class="panel-heading list-panel-heading">
                <h1 class="panel-title list-panel-title">Properties</h1>
            </div>
            <div class="panel-body">
                <table id="datatable" class="table table-striped table-bordered" style="width:100%;">
                    <thead>
                        <tr>
                            <th>BarCode</th>
                            <th>Manufacturer</th>
                            <th>Building</th>
                            <th>Quantity</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</div>

@section Scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            var datatableInstance = $('#datatable').DataTable({
                serverSide: true,
                processing: true,
                "ajax": {
                    "url": "@Url.Action("Get","Asset")"
                },
                lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                columns: [
                    { 'data': 'BarCode' },
                    { 'data': 'Manufacturer' },
                    {
                        'data': 'Building',
                        'searchable': true,

                    },
                    {
                        'data': 'Quantity',
                        'searchable': true,
                        'render': function (Quantity) {
                            return "$ " + Quantity;
                        }
                    },
                ],

            });

        });  
    </script>

}

我使用了JQuery数据表,如果行数少(少于100000,则代码工作正常),但是如果行数多,则变得很糟糕

在下一行中花费的时间太长了

var filteredCount = query.Count();

如何提高性能

1 个答案:

答案 0 :(得分:0)

在我看来,改为执行“ var totalCount = query.Count();”尝试制作一个对表进行计数的sql语句,可能会获得更好的性能。

var totalCount = _context.SqlQuery(“从yourTable中选择count(0)”)。FirstOrDefault();

我还没有使用Count()测试性能,但是使用Distinc()进行了比较。

希望有帮助