asp.net – Web API可查询 – 如何应用AutoMapper?

我有一个简单的WebApi方法像这样装饰了OData可查询属性
[Queryable]
    public virtual IQueryable<PersonDto> Get()
    {
        return uow.Person().GetAll()); // Currently returns Person instead of PersonD
    }

我想做的是在WebAPI将结果转换为JSON之前,使用AutoMapper将查询的结果从Person类型转换为PersonDto。

有人知道我能做到吗我知道,我可以在GetAll()调用之后应用Mapper.Map,然后转换回IQueryable,但是这将导致在应用OData过滤器之前返回和映射整个表(不好!)。

看来,这个问题ASP.NET Web API return queryable DTOs?涵盖了相同的问题(请参阅第二个回应来获得更好的答案),其中建议是使用自定义MediaTypeFormatter在链末尾使用AutoMapper,但是我不知道如何做到这一点我见过的例子

任何帮助将得到感谢!

– 更多信息

我查看了IQueryable的源代码,但不幸的是,我看不到任何方法利用这个代码。我设法写了一个似乎工作的附加过滤器,但并不一定不优雅。

public class PersonToPersonDtoConvertAttribute : ActionFilterattribute
{
    public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
    {
        HttpResponseMessage response = actionExecutedContext.Response;

        if (response != null)
        {
            ObjectContent responseContent = response.Content as ObjectContent;
            var query = (responseContent.Value as IQueryable<Student>).ToList();
            response.Content = new ObjectContent<IEnumerable<StudentResource>>(query.ToList().Select(Mapper.Map<Person,PersonDto>),responseContent.Formatter);
        }
    }
}

然后我已经装饰了这样的动作

[Queryable]
    [PersonToPersonDtoConvert]
    public IQueryable<Person> Get()
    {
        return uow.GetRepo<IRepository<Person>>().GetAll();
    }

解决方法

一个更好的解决方案。尝试这个:
public virtual IQueryable<PersonDto> Get(ODataQueryOptions<Person> query)
{
    var people = query.ApplyTo(uow.Person().GetAll());
    return ConvertToDtos(people);
}

这将确保查询运行在Person而不是PersonDTO。如果您希望通过属性而不是代码进行转换,那么您仍然希望实现类似于您所提供的操作过滤器。

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...