2016-06-14 87 views
0

我正在使用OData v5/Web API 2.2創建一個端點,它將返回每個公司的員工列表。OData分頁與擴展問題

當我嘗試在使用OData $ expand屬性的同時實現服務器端分頁時出現問題。當我嘗試撥打電話,以

http://localhost:60067/Companies?$展開;員工

我得到說「無法找到名爲‘員工’的類型「System.Web.OData.Query.Expressions屬性是一個錯誤.SelectAllExpand_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

找出問題所在。我們重寫了代碼中某處的EnableQuery屬性,並將其稱爲EnableMappedQuery並將其應用於控制器。因此,而不是[EnableQuery(PageSize = 10)]我應該有[EnableMappedQuery(PageSize = 10)]。

0

EnableQuery屬性做很多工作,

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,失敗的話,它可以找不到擴展屬性,我的建議只是返回原來的Company並讓EnableQuery爲你做好重置工作,ODataQueryOption中的參數也是不需要的。

如果你真的在做一些GetCompanies定製工作,不需要EnableQuery申請你,你可以在ODataQuerySettings當你調用方法ODataQueryOptions.ApplyTo(IQueryable的,ODataQuerySettings)添加每頁。