我正在尝试将OData与.NET Core WebApi项目结合使用。因为我想控制输出的格式,所以我采取了一种可能不是很常规的方法,并且在我的操作中,我收到了一个应用于数据源的ODataQueryOptions输入-通过EF Core公开的CosmosDb集合。 在代码方面,我在启动时有类似的东西:
public void ConfigureServices(IServiceCollection services)
{
....
services.AddOData();
....
}
和
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
....
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.EnableDependencyInjection();
/* tried even
endpoints.EnableDependencyInjection(builder =>
{
builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, typeof(ODataUriResolver), sp => new StringAsEnumResolver());
});
*/
endpoints.Filter();
});
...
}
控制器非常简单:
namespace Tacx.Backend.Activity.Api.Controllers
{
[Route("api/activities/search")]
[ApiController]
public class SearchController : ControllerBase
{
private readonly ActivityContext _db;
private readonly IMapper _mapper;
public SearchController(ActivityContext db, IMapper mapper)
{
_db = db;
_mapper = mapper;
}
[HttpGet]
public async Task<List<ActivitySummaryDTO>> GetActivities(ODataQueryOptions<Domain.Models.Activity> opts)
{
try
{
var odataResult = opts.ApplyTo(_db.Activities.AsQueryable());
var activities = odataResult as IQueryable<Domain.Models.Activity>;
var activitiesDto= _mapper.Map<List<ActivitySummaryDTO>>(activities);
return activitiesDto;
}
catch(Exception ex)
{
throw ex;
}
}
}
}
如果我对字符串,GUID或数字的属性进行过滤,则此方法就很好。每当我尝试对一个枚举字段(它们以字符串形式存储在CosmosDB中)运行过滤器时,我都会遇到问题...
我一直在尝试使用$filter=MyPropertyEnum eq 'enumValue'
之类的过滤器,但收到错误消息:Invalid cast from 'System.Int32' to 'Activity.Domain.Enums.MyPropertyEnum'.
我一直在尝试Google寻求解决方案,但到目前为止找不到任何东西……欢迎任何帮助或建议。 谢谢!