我使用OData v5 / Web API 2.2来创建一个端点,该端点将返回每个公司的员工列表。
当我尝试在使用OData $ expand属性的同时实现服务器端分页时,会出现问题。当我试图打电话
时http://localhost:60067/Companies?$扩大=雇员
我收到一条错误消息,指出"无法找到名为'员工' on type' System.Web.OData.Query.Expressions.SelectAllAndExpand_1OfCompanyApiModel'"
但是,当我删除EnableQuery属性时,对端点的调用或当我没有扩展它时,它按预期工作。有没有人知道我做错了什么?我已经谷歌搜索了一段时间,但没有找到任何东西。
以下是一些代码段 -
数据模型:
public class CompanyApiModel
{
[Key]
public Guid CompanyGuid { get; set; }
[Required]
public string Name { get; set; }
// other properties
public List<EmployeeApiModel> Employees { get; set; }
}
public class EmployeeApiModel
{
[Key]
public Guid EmployeeGuid { get; set; }
[Required]
public string Name { get; set; }
// other properties
}
CompaniesController.cs :
[EnableQuery(PageSize = 10)] // If I comment this out everything works
//[EnableQuery] // This fails as well
public IHttpActionResult Get(ODataQueryOptions<CompanyApiModel> queryOptions)
{
var companies = GetCompanies(queryOptions);
return Ok(companies);
// return Ok(companies.AsQueryable()); // This doesn't work either
}
WebApiConfig.cs:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
var routingConventions = ODataRoutingConventions.CreateDefault();
routingConventions.Insert(0, new OptionsRoutingConvention());
config.MapODataServiceRoute("odata", null, GetEdmModel(), new DefaultODataPathHandler(), routingConventions);
// below code allows endpoints to respond with either XML or JSON, depending on accept header preferences sent from client
// (default in absence of accept header is JSON)
var odataFormatters = ODataMediaTypeFormatters.Create();
config.Formatters.InsertRange(0, odataFormatters);
config.EnsureInitialized();
}
public static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.Namespace = "Demos";
builder.ContainerName = "DefaultContainer";
builder.EntitySet<CompanyApiModel>("Companies");
builder.EntitySet<EmployeeApiModel>("Employees");
var edmModel = builder.GetEdmModel();
return edmModel;
}
}
答案 0 :(得分:0)
EnableQuery Attribute做了很多工作,
1. it will validate the queryoption for you.
2. it will apply the queryoption for you.
3. it can add some querysettings like PageSize.
您的方案无效是因为您的GetCompanies
已经应用了queryoption,所以当EnableQuery获取结果并再次应用queryoption时,它会失败,它无法找到expand属性,我的建议是只需返回原始Company
并让EnableQuery为您重置工作,也不需要参数ODataQueryOption
。
如果你真的在GetCompanies
做一些自定义工作并且不需要EnableQuery来申请,你可以在调用方法ODataQueryOptions.ApplyTo时在ODataQuerySettings
中添加PageSize(IQueryable,ODataQuerySettings )。
答案 1 :(得分:0)
找出问题所在。我们在代码中的某处覆盖了EnableQuery属性,并将其称为EnableMappedQuery并将其应用于控制器。因此,我应该使用[EnableQuerypedQuery(PageSize = 10)]而不是[EnableQuery(PageSize = 10)]。