【发布时间】:2016-03-20 23:54:51
【问题描述】:
有 2 个类,Foo 和 Bar。 Foo 对象中嵌套了一个 Bar 对象。
public class Foo {
public Guid FooId { get; set; }
public string FooName { get; set; }
[ForeignKey("Bar")]
public Guid BarId { get; set; }
public virtual Bar Bar { get; set; }
}
public class Bar {
public Guid BarId { get; set; }
public string BarName { get; set; }
}
public class FooBarContext : DbContext {
public DbSet<Foo> Foos { get; set; }
public DbSet<Bar> Bars { get; set; }
}
public class FooDTO {
public Guid FooId { get; set; }
public string FooName { get; set; }
public Guid BarId { get; set; }
public string BarName { get; set; }
}
我的问题是:我能否以某种方式将 FooDTO 的 OData 查询转换为 Foo 的 OData 查询,以便将其应用于 Foos DbSet?
例如,我想通过 BarName 进行查询,它最终来自嵌套的 Bar 对象。
GET /Foos?$filter=BarName eq 'Bar2'
这是处理查询的控制器和操作
public class FoosController {
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions) {
// translate filter FooDTO.BarName to filter Foo.Bar.Name
// ODataQueryOptions<Foo> fooQueryOptions = ....
using (var context = new FooBarContext()) {
return fooQueryOptions.ApplyTo(context.Foos);
}
}
}
谢谢。
【问题讨论】:
-
你的问题解决了吗?
-
@Tymek 抱歉回复晚了。我最终实施了自己的解决方案,放弃了 OData。但是,如果您想使用 OData,据我所知,仅有的 2 个选项是 AutoMapper,以及自己解析和构建查询。解析OData查询请参考这篇文章ben-morris.com/…
标签: c# entity-framework asp.net-web-api odata