将lambda表达式与属性路径相结合

时间:2022-10-28 18:55:02

I'd need to be able to combine 2 lambda expressions into 1:

我需要能够将2个lambda表达式组合成1:

This would serve me to create an extension to the type-safe includes (for EF).

这将使我能够创建类型安全包含(对于EF)的扩展。

Now you can do:

现在你可以这样做:

context.House
.Include(x => x.Doors.Doorknobs)

I'd like to be able to split up the above statement into different methods.

我希望能够将上述陈述分成不同的方法。

something like IncludeDoorKnobs(query, expressionFromRoot, expressionFromCurrentToChild)

像IncludeDoorKnobs(query,expressionFromRoot,expressionFromCurrentToChild)之类的东西

Then I'd like to - Include the combined expression to the query - Include extra childs (from current) to that query - Call other similar methods, including another part of the tree.

然后我想 - 将组合表达式包含在查询中 - 包含额外的子项(从当前)到该查询 - 调用其他类似的方法,包括树的另一部分。

My knowledge of Lambda's clearly comes short, and I'd really need to get into them soon, but for now, I have to resort tho SOF...

我对Lambda的了解显然很短暂,我真的需要很快进入它们,但是现在,我不得不求助于SOF ......

1 个解决方案

#1


With LINQ-to-SQL this would be trivial; you just use Expression.Invoke to tell it to use an existing sub-expression (with parameter substitution) at the given point. However, EF doesn't (or didn't last time I checked) support this.

使用LINQ-to-SQL,这将是微不足道的;您只需使用Expression.Invoke告诉它在给定点使用现有的子表达式(带参数替换)。但是,EF没有(或者上次我没检查过)支持这个。

Unfortunately, the process for combining two expressions without this is... complex; you essentially need to completely re-build the inner tree, doing manual substitution for things like parameters. I did have some code that did this, but it is far from simple (and it isn't "to hand").

不幸的是,没有这个组合两个表达式的过程是......复杂的;你基本上需要完全重新构建内部树,手动替换参数之类的东西。我确实有一些代码可以做到这一点,但它远非简单(并且它不是“手工”)。

But I wonder: is it really worth the complexity?

但我想知道:它真的值得复杂吗?

#1


With LINQ-to-SQL this would be trivial; you just use Expression.Invoke to tell it to use an existing sub-expression (with parameter substitution) at the given point. However, EF doesn't (or didn't last time I checked) support this.

使用LINQ-to-SQL,这将是微不足道的;您只需使用Expression.Invoke告诉它在给定点使用现有的子表达式(带参数替换)。但是,EF没有(或者上次我没检查过)支持这个。

Unfortunately, the process for combining two expressions without this is... complex; you essentially need to completely re-build the inner tree, doing manual substitution for things like parameters. I did have some code that did this, but it is far from simple (and it isn't "to hand").

不幸的是,没有这个组合两个表达式的过程是......复杂的;你基本上需要完全重新构建内部树,手动替换参数之类的东西。我确实有一些代码可以做到这一点,但它远非简单(并且它不是“手工”)。

But I wonder: is it really worth the complexity?

但我想知道:它真的值得复杂吗?