我最近在我的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响应。我得到的唯一失败消息来自控制台:
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上找到指向完整项目的链接。如果您找到任何答案,请告诉我们!
答案 0 :(得分:0)
我能够通过一些小的修订来使它工作。
更新域模型:
public class ProductEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<Order> 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; }
}
在路由生成器上手动启用扩展:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, SalesModelBuilder modelBuilder)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc(routeBuilder =>
{
routeBuilder.Expand().Select();
routeBuilder.MapODataServiceRoute("ODataRoutes", "odata",
modelBuilder.GetEdmModel(app.ApplicationServices));
});
}
使用以下查询: