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。如果您希望通过属性而不是代码进行转换,那么您仍然希望实现类似于您所提供的操作过滤器。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc – 在MVC4中绑定的正确方法
- asp.net-mvc – 使用View.Render方法将MVC视图转换为字符串
- asp.net – 未捕获错误:在初始化之前无法在弹出窗口上调用
- asp.net – 无法将第二个自引用FK添加到模型,导致无法确定主
- asp.net-mvc – site.css不适用于我的示例网站
- asp.net – ASP .NET AJAX和JQuery
- asp.net-web-api – 使用ASP.NET WebAPI消费Atlassian Webh
- Asp.net托管相当于Dreamhost(定价,功能和支持)
- ML.NET技术研究系列-2聚类算法KMeans
- asp.net-mvc – ASP.net身份在删除外部帐户后停止分发外部C
- asp.net – 可以使用__doPostBack()吗?
- .net – 设置runat = server时输入名称和ID更改
- asp.net-mvc-3 – EF 4.1上的MvcMiniProfiler代码
- asp.net-web-api – ASP.NET Web API RTM和子域路
- asp.net – ajax中的Updatepanel总是运行page_lo
- 使用ASP.Net Web API进行多部分表单POST
- razor – 使用ActionLink将null参数传递给控制器
- asp.net – 模型项的类型为CookMeIndexViewModel
- asp.net – 帮助理解模仿
- asp.net – 限制关于AJAX调用的视图状态信息