加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 18:39:54 所属栏目:asp.Net 来源:网络整理
导读:我有一个简单的WebApi方法像这样装饰了OData可查询属性。 [Queryable] public virtual IQueryablePersonDto Get() { return uow.Person().GetAll()); // Currently returns Person instead of PersonD } 我想做的是在WebAPI将结果转换为JSON之前,使用AutoMa
我有一个简单的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。如果您希望通过属性而不是代码进行转换,那么您仍然希望实现类似于您所提供的操作过滤器。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读