我正在尝试为 IQueryable 自动生成参数。这样我就可以从我的 Entity Framework 代码优先数据上下文中选择实体,而无需编写和连接大量繁琐的映射代码。
我的项目包含一堆看起来像这样的 DTO:-
class FooDto
{
public string SomeProperty { get; set; }
public string SomeOtherProperty { get; set; }
}
还有一堆看起来像的实体:-
class Foo
{
public string SomeProperty { get; set; }
public string SomeOtherProperty { get; set; }
// Some other properties here.
}
DTO 包含识别我的数据库中某些实体子集所必需的字段。我使用 DTO 查询实体的 IQueryable:-
var result = queryable.Where(
x => x.SomeProperty == dto.SomeProperty
&& x.SomeOtherProperty == dto.SomeOtherProperty)
实际属性各不相同,但查询始终是“实体上的所有属性与 DTO 上的所有匹配属性匹配” 的形式。没有更复杂的查询对象功能。
有许多 DTO 和实体。创建/维护和连接所有这些谓词是一个具有挑战性的架构问题。我们目前正在使用策略模式:-
public class FooDtoSelectStrategy : ISelectStrategy<FooDto, FooEntity>
{
public Func<FooEntity, bool> GetPredicate(FooDto dto)
{
return x => x.SomeProperty == dto.SomeProperty
&& x.SomeOtherProperty == dto.SomeOtherProperty;
}
}
还有一堆 ninject 绑定(bind),但我们已经有几十个这样的绑定(bind),随着我们领域的扩展,我们正在寻找数百个。
我们遇到了类似的挑战,将值从实体映射到我们使用 AutoMapper 解决的 DTO。
automapper(或类似工具)能否创建这些谓词并允许我们实现单个 GenericPredicateProvider<TDto, TEntity>
?
最佳答案
你所做的实际上叫做 specification pattern .所以你基本上重新设计了轮子,提出了一个略有不同但基本相同的轮子。
您可以使用 T4 模板之类的东西来自动生成这些 Predicate 提供程序,但是您在一个对象中查询相同的对象似乎有点愚蠢。您已经有了该对象,那么为什么还要查询所有字段以获得完全相同的对象?
关于c# - 基于DTO自动生成EF "where"子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13052970/