2017-04-06 103 views
1

相關實體我有這些類:自動擴展的OData與控制器

public class Items 
    { 
    [Key] 
    public Guid Id { get; set; } 
    public string ItemCode { get; set; } 
    public decimal SalesPriceExcl { get; set; } 
    public decimal SalesPriceIncl { get; set; } 

    public virtual ICollection<ItemPrice> SalesPrices { get; set; } 

    public Items() 
    { 
     SalesPrices = new HashSet<App4Sales_ItemPrice>(); 
    } 
} 

public class ItemPrice 
{ 
    [Key, Column(Order = 0), ForeignKey("Items")] 
    public Guid Id { get; set; } 
    public virtual Items Items { get; set; } 

    [Key, Column(Order=1)] 
    public Guid PriceList { get; set; }   
    public decimal PriceExcl { get; set; } 
    public decimal PriceIncl { get; set; } 
    public decimal VatPercentage { get; set; }   

} 

我要查詢的項目,並自動獲得ITEMPRICE集合。

我創建了一個OData的V3控制器:

// GET: odata/Items 
    //[Queryable] 
    public IQueryable<Items> GetItems(ODataQueryOptions opts) 
    { 
     SelectExpandQueryOption expandOpts = new SelectExpandQueryOption(null, "SalesPrices", opts.Context); 
     Request.SetSelectExpandClause(expandOpts.SelectExpandClause); 
     return expandOpts.ApplyTo(db.Items.AsQueryable(), new ODataQuerySettings()) as IQueryable<Items>; 


    } 

但我得到的錯誤: 「無法序列空進」

是的,有些項目沒有ITEMPRICE名單。

我可以通過這個錯誤,還是我可以做一些不同的事情?

親切的問候

的Jeroen

我發現底層錯誤是: 無法轉換 類型的對象 'System.Data.Entity.Infrastructure.DbQuery 1[System.Web.Http.OData.Query.Expressions.SelectExpandBinder+SelectAllAndExpand 1 [.Models.Items]]' 鍵入'.Models.Items'。

回答

0

我已經解決了它,我碰到這個崗位來了以後:http://www.jauernig-it.de/intercepting-and-post-processing-odata-queries-on-the-server/

這是我現在的控制器:

SelectExpandQueryOption expandOpts = new SelectExpandQueryOption(null, "SalesPrices", opts.Context); 

     Request.SetSelectExpandClause(expandOpts.SelectExpandClause); 

     var result = expandOpts.ApplyTo(db.Items.AsQueryable(), new ODataQuerySettings()); 
     var resultList = new List<Items>(); 

     foreach (var item in result) 
     { 
      if (item is Items) 
      { 
       resultList.Add((Items)item); 
      } 
      else if (item.GetType().Name == "SelectAllAndExpand`1") 
      { 
       var entityProperty = item.GetType().GetProperty("Instance"); 
       resultList.Add((Items)entityProperty.GetValue(item)); 
      } 
     } 


     return resultList.AsQueryable(); 

的Jeroen

0

GetItems([FromODataUri] ODataQueryOptions queryOptions)

+0

這會在調用時導致錯誤,請參閱編輯基礎錯誤 –