我有一个简单的 Web API 端点,可以接受传入的 OData 查询:
public IActionResult GetProducts(ODataQueryOptions<ProductDTO> options)
{
var results = DomainLayer.GetProducts(options);
return Ok(results);
}
我特别希望能够查询ProductDTO
对象并能够根据 DTO 表示的属性进行过滤或排序。
我的设计问题是我想利用 OData 库的过滤器解析/应用逻辑,但我不想暴露我的数据库绑定ProductEntity
我的 Web API 的对象AND我不想退货IQueryable
从我的DataAccessLayer
, only IEnumerable
s.
我想做的就是提取Expression
来自FilterQueryOption
传入的属性ODataQueryOptions
所以我可以使用 AutoMapper 的表达式映射功能来映射表达式Expression<Func<ProductDTO, bool>>
to a Expression<Func<Product, bool>>
然后最后到一个Expression<Func<ProductEntity, bool>>
然后我将把它传递到.Where()
打电话给我的Table<ProductEntity>
(希望)过滤器应用于我的 SQL 数据库(通过 Linq-2-SQL)然后我将其一路转换回 DTO 对象。
我遇到的最大的亮点是queryable.Expression
正在返回一个MethodCallExpression
而不是一个Expression<Func<ProductDTO, bool>>
正如我所期望的,这意味着我无法像我计划的那样使用 AutoMapper 映射表达式......
我该如何解决这个问题?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNet.OData.Query;
using AutoMapper.Extensions.ExpressionMapping;
using AutoMapper.QueryableExtensions;
namespace ProductApp
{
public class DomainLayer
{
public IEnumerable<ProductDTO> GetProductsByEntityOptions(ODataQueryOptions<ProductDTO> options)
{
var mapper = MyMapper.GetMapper();
// This is the trick to get the expression out of the FilterQueryOption...
IQueryable queryable = Enumerable.Empty<ProductDTO>().AsQueryable();
queryable = options.Filter.ApplyTo(queryable, new ODataQuerySettings());
var exp = (MethodCallExpression) queryable.Expression; // <-- This comes back as a MethodCallExpression...
// Map the expression to my intermediate Product object type
var mappedExp = mapper.Map<Expression<Func<Product, bool>>>(exp); // <-- But I want it as a Expression<Func<ProductDTO, bool>> so I can map it...
IEnumerable<Product> results = _dataAccessLayer.GetProducts(mappedExp);
return mapper.Map<IEnumerable<ProductDTO>>(results);
}
}
public class DataAccessLayer
{
public IEnumerable<Product> GetProducts(Expression<Func<Product, bool>> exp)
{
var mapper = MyMapper.GetMapper();
var mappedExp = mapper.Map<Expression<Func<ProductEntity, bool>>>(exp);
IEnumerable<ProductEntity> result = _dataContext.GetTable<ProductEntity>().Where(mappedExpression).ToList();
return mapper.Map<IEnumerable<Product>>(result);
}
}
}
参考:
- 我在那里找到了从过滤器中获取表达式的技巧:https://stackoverflow.com/a/16447514/1504964
- 相关的 GitHub 问题:https://github.com/OData/WebApi/issues/33