What is the best approach to load/filter/order a Kendo grid with the following classes:
Domain:
public class Car
{
public virtual in
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.
Create the viewmodel you wish to use
public class MyViewModelVM
{
public int Id { get; set; }
public string MyFlattenedProperty { get; set; }
}
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
Configure AutoMapper to map your ORM view class to your viewmodel
Mapper.CreateMap<MyDatabaseView, MyViewModelVM>();
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<MyViewModelVM>(r));
return Json(result);
}
return Json(new List<MyViewModelVM>().ToDataSourceResult(request));
}
It's a bit of overhead but it will help you in achieve performance on two levels when working with large datasets:
Something about that seems weird. You told Kendo UI to make a grid for CarViewModel
.Grid<CarViewModel>()
and told it there is an IsActive
column:
columns.Bound(c => c.IsActive);
but CarViewModel
doesn't have a column by that name:
public class CarViewModel
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string IsActiveText { get; set; }
}
My guess is that Kendo is passing up the field name from the CarViewModel IsActiveText
, but on the server you are running ToDataSourceResult()
against Car
objects (an IQueryable<Car>
), which do not have a property by that name. The mapping happens after the filtering & sorting.
If you want the filtering and sorting to happen in the database, then you would need to call .ToDataSourceResult()
on the IQueryable before it runs against the DB.
If you have already fetched all your Car
records out of the DB, then you can fix this by doing your mapping first, then calling .ToDataSourceResult()
on an IQueryable<CarViewModel>
.
I came across this same issue and after lots of research I resolved it permanently by using AutoMapper.QueryableExtensions library. It has an extension method that will project your entity query to your model and after that you can apply ToDataSourceResult extension method on your projected model.
public ActionResult GetData([DataSourceRequest]DataSourceRequest request)
{
IQueryable<CarModel> entity = getCars().ProjectTo<CarModel>();
var response = entity.ToDataSourceResult(request);
return Json(response,JsonRequestBehavior.AllowGet);
}
Remember to configure Automapper using CreateMap.
Note: Here getCars will return IQueryable result car.
I don't like the way Kendo has implemented "DataSourceRequestAttribute" and "DataSourceRequestModelBinder", but thats another story.
To be able to filter/sort by VM properties which are "flattened" objects, try this:
Domain model:
public class Administrator
{
public int Id { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
}
View model:
public class AdministratorGridItemViewModel
{
public int Id { get; set; }
[Displaye(Name = "E-mail")]
public string User_Email { get; set; }
[Display(Name = "Username")]
public string User_UserName { get; set; }
}
Extensions:
public static class DataSourceRequestExtensions
{
/// <summary>
/// Enable flattened properties in the ViewModel to be used in DataSource.
/// </summary>
public static void Deflatten(this DataSourceRequest dataSourceRequest)
{
foreach (var filterDescriptor in dataSourceRequest.Filters.Cast<FilterDescriptor>())
{
filterDescriptor.Member = DeflattenString(filterDescriptor.Member);
}
foreach (var sortDescriptor in dataSourceRequest.Sorts)
{
sortDescriptor.Member = DeflattenString(sortDescriptor.Member);
}
}
private static string DeflattenString(string source)
{
return source.Replace('_', '.');
}
}
Attributes:
[AttributeUsage(AttributeTargets.Method)]
public class KendoGridAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
foreach (var sataSourceRequest in filterContext.ActionParameters.Values.Where(x => x is DataSourceRequest).Cast<DataSourceRequest>())
{
sataSourceRequest.Deflatten();
}
}
}
Controller action for Ajax data load:
[KendoGrid]
public virtual JsonResult AdministratorsLoad([DataSourceRequestAttribute]DataSourceRequest request)
{
var administrators = this._administartorRepository.Table;
var result = administrators.ToDataSourceResult(
request,
data => new AdministratorGridItemViewModel { Id = data.Id, User_Email = data.User.Email, User_UserName = data.User.UserName, });
return this.Json(result);
}
I followed the suggestion of CodingWithSpike and it works. I created an extension method for the DataSourceRequest class:
public static class DataSourceRequestExtensions
{
/// <summary>
/// Finds a Filter Member with the "memberName" name and renames it for "newMemberName".
/// </summary>
/// <param name="request">The DataSourceRequest instance. <see cref="Kendo.Mvc.UI.DataSourceRequest"/></param>
/// <param name="memberName">The Name of the Filter to be renamed.</param>
/// <param name="newMemberName">The New Name of the Filter.</param>
public static void RenameRequestFilterMember(this DataSourceRequest request, string memberName, string newMemberName)
{
foreach (var filter in request.Filters)
{
var descriptor = filter as Kendo.Mvc.FilterDescriptor;
if (descriptor.Member.Equals(memberName))
{
descriptor.Member = newMemberName;
}
}
}
}
Then in your controller, add the using
to the extension class and before the call to ToDataSourceResult(), add this:
request.RenameRequestFilterMember("IsActiveText", "IsActive");
František's solution is very nice! But be careful with casting Filters to FilterDescriptor. Some of them can be composite.
Use this implementation of DataSourceRequestExtensions instead of František's:
public static class DataSourceRequestExtensions
{
/// <summary>
/// Enable flattened properties in the ViewModel to be used in DataSource.
/// </summary>
public static void Deflatten(this DataSourceRequest dataSourceRequest)
{
DeflattenFilters(dataSourceRequest.Filters);
foreach (var sortDescriptor in dataSourceRequest.Sorts)
{
sortDescriptor.Member = DeflattenString(sortDescriptor.Member);
}
}
private static void DeflattenFilters(IList<IFilterDescriptor> filters)
{
foreach (var filterDescriptor in filters)
{
if (filterDescriptor is CompositeFilterDescriptor)
{
var descriptors
= (filterDescriptor as CompositeFilterDescriptor).FilterDescriptors;
DeflattenFilters(descriptors);
}
else
{
var filter = filterDescriptor as FilterDescriptor;
filter.Member = DeflattenString(filter.Member);
}
}
}
private static string DeflattenString(string source)
{
return source.Replace('_', '.');
}
}