How to use Kendo UI Grid with ToDataSourceResult(), IQueryable, ViewModel and AutoMapper?

前端 未结 6 1653
轻奢々
轻奢々 2021-02-02 01:00

What is the best approach to load/filter/order a Kendo grid with the following classes:

Domain:

public class Car
{
    public virtual in         


        
6条回答
  •  [愿得一人]
    2021-02-02 01:23

    One good way to solve it if you use Telerik Data Access or any other IQueryable enabled interface/ORM over your data, is to create views directly in your database RDBMS that map one-to-one (with automapper) to your viewmodel.

    1. Create the viewmodel you wish to use

      public class MyViewModelVM
      {
          public int Id { get; set; }
          public string MyFlattenedProperty { get; set; }
      }
      
    2. Create a view in your SQL Server (or whatever RDBMS you're working with) with columns exactly matching the viewmodel property names, and of course build your view to query the correct tables. Make sure you include this view in your ORM classes

      CREATE VIEW MyDatabaseView
      AS
      SELECT
      t1.T1ID as Id,
      t2.T2SomeColumn as MyFlattenedProperty
      FROM MyTable1 t1
      INNER JOIN MyTable2 t2 on t2.ForeignKeyToT1 = t1.PrimaryKey
      
    3. Configure AutoMapper to map your ORM view class to your viewmodel

      Mapper.CreateMap();
      
    4. In your Kendo grid Read action, use the view to build your query, and project the ToDataSourceQueryResult using Automapper

      public ActionResult Read([DataSourceRequest]DataSourceRequest request)
      {
          if (ModelState.IsValid)
          {
              var dbViewQuery = context.MyDatabaseView;
      
              var result = dbViewQuery.ToDataSourceResult(request, r => Mapper.Map(r));
      
              return Json(result);
          }
      
          return Json(new List().ToDataSourceResult(request));
      }
      

    It's a bit of overhead but it will help you in achieve performance on two levels when working with large datasets:

    • You are using native RDBMS views which you can tune yourself. Will always outperform complex LINQ queries you build in .NET
    • You can leverage the Telerik ToDataSourceResult benefits of filtering, grouping, aggregating, ...

提交回复
热议问题