我正在尝试使用OData,而我在使用$ expand函数时遇到了问题。
我有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; }
如果我想检索一个事件并展开订单,然后再展开门票,那就没有问题了。只要我使用Event作为起点。
但是,如果我选择一个订单(工作正常)并想要扩展Tickets,我会收到以下错误: “'DbQuery`1'无法使用ODataMediaTypeFormatter进行序列化。”
同样,如果我想检索特定订单的故障单,则只会发生这种情况。如果我选择事件并从那里扩展,一切正常。
有谁知道我做错了什么?我似乎无法弄明白。
答案 0 :(得分:0)
你应该实现两件事:
1)您应该将ODataConventionModelBuilder与MapODataServiceRoute结合使用。 因此,将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 Orders控制器中:
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);
}
}
}