2017-02-16 70 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); 
     } 
    } 

}