【发布时间】:2018-11-21 02:36:42
【问题描述】:
我最近在我的 ASP .NET Core Web API 中实现了 OData。只要我直接返回数据库模型,我就找到了成功。但是,当我尝试返回域模型时,我遇到了麻烦。
基本问题涉及将数据类映射到域类,同时保持 IQueryable 返回类型。虽然我发现使用 AutoMapper 的 MapTo 扩展方法取得了部分成功,但我发现使用 $extend 方法扩展同时也是域对象的实体集合时并不成功。
我创建了一个示例项目来说明这个问题。您可以在 github here 上查看或下载完整的项目。请参阅下面的说明。
给定以下两个数据库类:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<Order> Orders { get; set; }
public Product() {
Orders = new Collection<Order>();
}
}
public class Order
{
public int Id { get; set; }
public Double Price { get; set; }
public DateTime OrderDate { get; set; }
[Required]
public int ProductId { get; set; }
public Product Product { get; set; }
}
还有以下领域模型...
public class ProductEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<OrderEntity> Orders { get; set; }
}
public class OrderEntity
{
public int Id { get; set; }
public Double Price { get; set; }
public DateTime OrderDate { get; set; }
[Required]
public int ProductId { get; set; }
public Product Product { get; set; }
}
还有产品控制器
public class ProductsController
{
private readonly SalesContext context;
public ProductsController(SalesContext context) {
this.context = context;
}
[EnableQuery]
public IQueryable<ProductEntity> Get() {
return context.Products
.ProjectTo<ProductEntity>()
.AsQueryable();
}
}
以下所有 OData 查询均通过:
- http://localhost:51004/odata/Products
- http://localhost:51004/odata/Orders
- http://localhost:51004/odata/Orders?$expand=产品
但是,以下查询没有通过:
- http://localhost:51004/odata/Products?$expand=订单
永远不会返回 HTTP 响应。我得到的唯一失败消息来自控制台:
System.InvalidOperationException: Sequence contains no matching element at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
最后,这里是映射配置文件的参考:
public static class MappingProfile
{
public static void RegisterMappings() {
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Order, OrderEntity>();
cfg.CreateMap<Product, ProductEntity>();
});
}
}
我可以通过在控制器中简单地返回 List 而不是 IEnumerable 来解决问题,但这当然会触发对数据库的大型查询,这将是性能密集型的。
如上所述,您可以在 Github here 上找到完整项目的链接。如果您找到任何答案,请告诉我!
【问题讨论】:
-
应该
OrderEntity有一个ProductEntity而不是Product属性?
标签: c# .net odata automapper iqueryable