我如何编写一个将 LINQ 转换为 SQL 的 ORM?
我已经创建了一个现有的 ORM,但我想用 LINQ 改进它,这样我就可以说:
MyORMObject.GetAll(o => o.firstName == "peter");
我脑子里的想法是系统将把它转换成查询。我想最困难的部分是读取解析到 LINQ 部分的内容。
我该怎么做?换句话说,我将如何(通过反射或其他方式)读取正在使用的 FirstName 属性及其所需的匹配项“Peter”?
How could I write an ORM that would convert LINQ into SQL?
I already have made an existing ORM, but I want to improve it with LINQ, so that I, for instance would be able to say:
MyORMObject.GetAll(o => o.firstName == "peter");
The idea in my head is that the system would then take that and convert it into a query. I guess the hard part is to read the stuff parsed into the LINQ part.
How do I do this? In other words, how would I (through Reflection or something else) read the FirstName
property being used, and its desired match, "Peter"?
发布评论
评论(2)
您将需要实现 IQueryable LINQ提供者。顺便说一下,您不会使用反射,您将使用 表达式树。
You are going to need to implement an IQueryable LINQ Provider. You won't be using reflection by the way, you'll be using Expression trees.
如果您的方法是
IEnumerable; GetAll(Expression>)
,则 lambda 表达式将被编译为表达式树,并带有Equals
子表达式,该子表达式又有一个包含FirstName
属性的MemberExpression
和一个包含字符串的ConstantExpression
。If your method is
IEnumerable<T> GetAll<T>(Expression<Func<T,bool>>)
, then the lambda expression will be compiled as an expression tree, with anEquals
sub-expression, which in turn has aMemberExpression
containing theFirstName
property, and aConstantExpression
containing the string.