2017-02-16 39 views
0

我正在嘗試使用OData,並遇到使用$ expand功能的問題。OData無法展開

我有3個實體:事件,訂購,票務

他們建立這樣的: 事件:

public int Id { get; set; } 
    public string UserId { get; set; } 
    public string Name { get; set; } 
    public string ShopName { get; set; } 
    public string ImageUrl { get; set; } 
    public string Description { get; set; } 
    public DateTimeOffset Start { get; set; } 
    public DateTimeOffset End { get; set; } 
    public virtual ICollection<Order> Orders { get; set; } = new Collection<Order>(); 

訂單:

public int Id { get; set; } 
    [ForeignKey("Event")] 
    public int EventId { get; set; } 

    public string CustomerFirstName { get; set; } 
    public string CustomerLastName { get; set; } 
    public string CustomerEmail { get; set; } 
    public string CustomerPhoneNumber { get; set; } 
    public string CustomerAddress { get; set; } 
    public string CustomerHouseNumber { get; set; } 

    public string TransactionId { get; set; } 
    public TransactionStatus Status { get; set; } 

    public DateTimeOffset OrderedOn { get; set; } 

    public virtual Event Event { get; set; } 
    public virtual ICollection<Ticket> Tickets { get; set; } = new Collection<Ticket>(); 

票:

public int Id { get; set; } 

    [ForeignKey("Order")] 
    public int OrderId { get; set; } 

    public string Barcode { get; set; } 

    public virtual Order Order { get; set; } 

如果我想檢索事件並展開訂單,然後展開故障單,則沒有問題。只要我以事件爲出發點。

但是,如果我選擇了一個Order(它工作正常)並且想要展開票證,我得到以下錯誤: 「'DbQuery`1'無法使用ODataMediaTypeFormatter進行序列化。

同樣,這隻會發生,如果我想檢索特定訂單的票證。如果我選擇事件並從那裏展開,那麼一切正常。

有誰知道我在做什麼錯?我似乎無法弄清楚。

回答

0

你應該執行兩件事情:

1)你應該結合MapODataServiceRoute使用ODataConventionModelBuilder。 因此改變你的OData配置爲:

 var builder = new ODataConventionModelBuilder(); 
     config.Count().Filter().OrderBy().Expand().Select().MaxTop(null); 
     builder.EntitySet<Ticket>("Tickets"); 
     builder.EntityType<Ticket>().HasKey(x => x.Id); 
     builder.EntitySet<Order>("Orders"); 
     builder.EntityType<Order>().HasKey(x => x.Id); 
     builder.EntitySet<Event>("Events"); 
     builder.EntityType<Event>().HasKey(x => x.Id); 
     IEdmModel model = builder.GetEdmModel(); 
     config.MapODataServiceRoute("ODataRoute", "odata", model); 

ODataConventionModelBuilder用於自動類映射到一個EDM模型。

2)將這個到您的OData訂單控制器:

public class OrdersController : ODataBaseController 
{ 
    ODataValidationSettings settings = new ODataValidationSettings() 
    { 
     AllowedFunctions = AllowedFunctions.AllFunctions 
    }; 

    [EnableQuery] 
    public IHttpActionResult Get(ODataQueryOptions<Order> options) 
    { 
     try 
     { 
      options.Validate(settings); 
      return Ok(dbContext.Orders); 
     } 
     catch (Exception ex) 
     { 
      return BadRequest(ex.Message); 
     } 
    } 

}