我开始了一个新的web api项目并使用了最新的OData库,但是我无法让$count
像以前的3.0版odota库那样工作。无论我尝试过什么,我总是回到json对象的数组,而不是它包含在一个对象中,该对象应该具有原始未过滤/已排序集合中项目总数的计数。
几乎所有其他内容都按预期工作,我可以使用$filter
,$top
,$skip
和$orderby
。我还没有尝试过其他任何事情。我也试过返回一个硬编码的实体列表而不是DbSet<Company>
,但这没有任何区别。
任何人都可以告诉我需要做些什么才能让它发挥作用?贝娄是回购所需的所有代码,我只展示了令人尊敬的代码(至少我认为是相关的代码)。如果我还需要展示其他任何内容,请询问。
packages.config
<package id="Microsoft.AspNet.WebApi" version="5.2.3" />
<package id="Microsoft.AspNet.OData" version="6.0.0" />
<package id="Microsoft.OData.Core" version="7.0.0" />
<package id="Microsoft.OData.Edm" version="7.0.0" />
公司模式
public sealed class Company {
public int CompanyId { get; set; }
public string Name { get; set; }
public CompanyState State { get; set; } // a simple int enum
public DateTime CreatedOn { get; set; }
}
WebApiConfig.cs
public static void Register(HttpConfiguration config) {
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
config.MapODataServiceRoute("odata", "odata", GetModel());
}
public static IEdmModel GetModel() {
var builder = new ODataConventionModelBuilder();
builder.EnableLowerCamelCase();
var companySet = builder.EntitySet<Model.Company>("Company").EntityType.HasKey(x => x.CompanyId);
return builder.GetEdmModel();
}
CompanyController.cs
[ODataRoutePrefix("Company")]
public sealed class CompanyController : ApiController {
private DbContext context;
public CompanyController(DbContext context) {
this.context = context;
}
[EnableQuery] // also tried with [EnableQuery(MaxNodeCount = 50, MaxTop = 100, PageSize = 100)]
[ODataRoute]
[HttpGet]
public IHttpActionResult Get()
{
return Ok(context.Set<Company>());
}
}
测试网址
http://localhost:35743/odata/Company/?$count=true&$top=3
结果
[{"companyId":2,"name":"Company 1","state":1,"createdOn":"2016-11-12T21:10:41"}
,{"companyId":3,"name":"Mars","state":0,"createdOn":"2016-11-12T21:10:41"}
,{"companyId":4,"name":"Veronica","state":0,"createdOn":"2016-11-12T21:10:41"}]
预期结果:
{
"@odata.context":"some local url",
"@odata.count": 9,
"value": [{"companyId":2,"name":"Company 1","state":1,"createdOn":"2016-11-12T21:10:41"}
,{"companyId":3,"name":"Mars","state":0,"createdOn":"2016-11-12T21:10:41"}
,{"companyId":4,"name":"Veronica","state":0,"createdOn":"2016-11-12T21:10:41"}]
}
答案 0 :(得分:2)
我没有从正确的控制器类型继承,我应该继承自ODataController
而不是ApiController
。
public sealed class CompanyController : ODataController
这样做解决了我遇到的问题和奇怪的副作用,就像不被忽视的属性一样。