首先,一些背景信息...我正在使用Telerik MVC Grid来显示数据。该网格期望将IEnumerable传递到他们的GridModel类中,我认为这会处理分页、排序、过滤等操作。
为了避免通过ajax以JSON格式传递此数据时出现循环引用,我需要将我的EF linq查询结果映射到视图模型对象...AutoMapper是我首选的方法,但是我想到的唯一涉及AutoMapper的解决方案会严重影响性能。
我有一个存储库将我的视图模型类型的IEnumerable返回给我的由网格调用的操作方法。
为了避免通过ajax以JSON格式传递此数据时出现循环引用,我需要将我的EF linq查询结果映射到视图模型对象...AutoMapper是我首选的方法,但是我想到的唯一涉及AutoMapper的解决方案会严重影响性能。
我有一个存储库将我的视图模型类型的IEnumerable返回给我的由网格调用的操作方法。
public IEnumerable<ResultViewModel> Search()
{
var person = _context.Persons;
//this works and is the best performance wise but could be made simpler with automapper
var result = person.Select(x => new ResultViewModel
{
FirstName = x.firstName,
LastName = x.lastName,
///etc...
});
//THIS IS SLOW but works
//var result = Mapper.Map<IEnumerable<Person>, IEnumerable<ResultViewModel>>(person);
//this does not work and errors at runtime
//var result = person.Select(x => Mapper.Map<Person, ResultViewModel>(x));
return result;
}
有没有什么办法可以在使用AutoMapper简化操作的同时保持我的性能?我猜想,使用AutoMapper的慢速版本是由于person
集合被枚举...然后稍后由Telerik Grid解析造成的。
person.Select(x => Mapper.Map<Person, ResultViewModel>(x))
中遇到了什么错误? - smartcavemanIQueryable
没有被评估。 jfar 的答案应该有效。 - smartcaveman