我当前正在进行的项目有一种方法可以定义数据库中对象的过滤器。
该过滤器是一个非常简单的类,其中包含将组合起来生成 SQL where
子句的条件。
现在的目标是使用此类来过滤 .Net 对象。例如,过滤器可能指定它所应用的对象的标题属性必须包含一些用户定义的字符串。
有哪些方法可以解决这个问题?过滤器应该返回什么而不是 sql where 子句,以及如何将其应用于对象?我已经考虑这个问题好几个小时了,但还不知道如何解决这个问题。一直在考虑反射、动态代码执行、构建表达式,但仍然没有找到起点。
The project I'm working currently on has a way to define a filter on objects from a database.
This filter is a pretty straightforward class containing criteria that will be combined to produce a SQL where
clause.
The goal now is to use this class to filter .Net objects as well. So for example the filter might specify that the title property of the object that it is applied to must contain some user-defined string.
What are ways to approach this problem? What should the filter return instead of the sql where-clause and how can it be applied to the object? I've been think about this for hours and don´t yet have even a slight idea how to solve this. Been thinking about reflection, dynamic code execution, building expressions but still haven´t found a starting point.
发布评论
评论(2)
这取决于所有用例是什么:)
如果您的数据库代码可以使用 LINQ,那么我可能会考虑返回
Expression>
,因为这可以通过以下方式应用.Where
到基于数据库的 LINQ 和 LINQ-to-Objects - 在后一种情况下只需调用:(数据库代码通常已经可查询,因此不需要 AsQueryable)。
这样做的一个坏处是不能保证特定的查询表达式适用于每个 LINQ 提供程序。
或者,您必须编写自己的基本查询语言或基本树结构。然后编写代码来转换为属性反射和 SQL。很多工作。
最后一个想法是只有两个不同的查询结果,并将这两个结果分开。因此,一个 SQL、一个
Predicate
或类似的。不过,它们存在不同步的风险。It depends on what all the use-cases are :)
If your DB code could use LINQ, then I might consider returning an
Expression<Func<YourEntity,bool>>
, as this can be applied via.Where
to both DB-based LINQ and LINQ-to-Objects - in the latter case simply by calling:(DB code is typically already queryable, so no AsQueryable is needed).
One bad thing about this is that there is no guarantee that a particular query expression will work on every LINQ provider.
Alternatively, you would have to write either your own basic query language, or a basic tree-structure. And then write code to translate to both property-reflection and SQL. Lots of work.
One final thought is to just have two different query results, and keep the two thigs separate. So one SQL, one
Predicate<T>
or similar. There is a risk of them being out of sync, though.如果你想像动态创建的 SQL where 子句一样,可以使用 动态LINQ来实现类似的效果。
If you want to do it a bit like the dynamically created SQL where clause, you could use Dynamic LINQ to achieve similar effects.