【发布时间】:2021-12-01 06:08:40
【问题描述】:
我有一个在 ASP.NET Core/5 框架之上用 C# 编写的 WebAPI。
我为我的 API 启用了odata。我正在尝试手动应用 odata 过滤器、order by 子句、选择列和扩展。
这是我尝试使用 ODataQueryOptions 手动构建查询的方式
protected IQueryable<TModel> BuildQuery(ODataQueryOptions<TModel> queryOptions, ODataQuerySettings settings)
{
IQueryable<TModel> query = DbSet;
if (queryOptions.SelectExpand != null)
{
var queryable = queryOptions.SelectExpand.ApplyTo(query, settings);
query = queryable.Cast<TModel>(); // this causes an error
}
if (queryOptions.Filter != null)
{
query = queryOptions.Filter.ApplyTo(query, settings) as IQueryable<TModel>; // this works!
}
if (queryOptions.OrderBy != null)
{
query = queryOptions.OrderBy.ApplyTo(query); // this works!
}
return query;
}
在我尝试扩展导航属性之前,上面的一切都很好。当我这样做时,我收到以下错误
System.InvalidOperationException: 'No coercion operator is defined between types 'Microsoft.AspNetCore.OData.Query.Wrapper.SelectAllAndExpand`1[MyModel]' and 'MyModel'.'
在定义IEdmModel 以构建导航关系时,是否需要进行某种映射?
如何正确地将IQueryable<Microsoft.AspNetCore.OData.Query.Wrapper.SelectAllAndExpand<TEntity>> 转换/转换为IQueryable<TEntity>?
这是SelectAllAndExpand背后的代码
【问题讨论】:
-
可能是 stackoverflow.com/questions/55636167/… 的副本,您无法将 selectexpand 查询转换为已定义的模型,您需要将其转换为动态,想象当
query是 IEnumerable时的 LINQ 表达式,例如 query.Select(t => new { t.Id, t.Name })这个查询不能被强制转换为 IEnumerable,因为它生成一个匿名动态类型,selectexpand 也是如此,所以你需要改变你的方法来考虑一个 IQueryable 返回。
标签: c# asp.net-core asp.net-web-api odata asp.net-web-api-odata