使用ODataQueryOptions时无法应用$ select

时间:2019-04-11 15:30:43

标签: c# asp.net-core entity-framework-core odata

我正在尝试通过EF Core和OData(7.1.0)实现对Sql Server的查询。

Action方法如下:

[HttpGet]
public IEnumerable<UserInfoDto> Get(ODataQueryOptions ops)
{
     return this.service.GetUserInfos(ops);
}

服务代码:

public List<UserInfoDto> GetUserInfos(ODataQueryOptions ops)
{
    using (var context = new EFContext())
    {
        var query = context.Users.Join(context.Customers, x => x.CustomerId, y => y.Id, (x, y) => new UserInfoDto
        {
            Id = x.Id,
            Name = x.Name,
            Age = x.Age,
            CustomerId = x.CustomerId,
            CustomerTitle = y.Title,
            CustomerDescription = y.Description
        });

        var result = ops.ApplyTo(query).Cast<UserInfoDto>().ToList();
        return result;
    }
}

启动Configute方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
     app.UseMvc(b => 
     {
         b.Count().Filter().OrderBy().Select().MaxTop(null);
         b.EnableDependencyInjection();
     });
}

但是,当我在查询中遇到$select(例如https://localhost:5001/api/userinfos?$select=id)时,而不是预期的结果是我得到了一个错误:

  

InvalidOperationException:类型之间未定义强制运算符   'Microsoft.AspNet.OData.Query.Expressions.SelectExpandBinder + SelectSome`1 [Oda   taApp.UserInfoDto]”和“ OdataApp.UserInfoDto”。



我想念什么?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

在对OData使用$select查询选项时,需要使用dynamic的IQueryable。

例如,想象下面的类:

public class Person {
    public int Id { get; set }
    public string Name { get; set; }
}

因此,如果您有一个不含$select的查询,则IQueryable将生成一个Person的集合,在每个项目中都有所有属性(id和name)。

但是,如果您使用$select=id查询,则每个项目将仅具有ID属性,并且无法将动态类型转换为Person类型。

换句话说,您不能使用$select并返回一个List<UserInfoDto>,您需要返回一个List<dynamic>而没有Cast方法,就像这样:

    var result = ops.ApplyTo(query) as IQueryable<dynamic>;
    return result.ToList();