实体框架中的 LINQ 投影
我发布了几个关于在急切加载查询中进行过滤的问题,我猜想 EF 不支持在 Include
语句内进行过滤,所以我想出了这个。
我想执行一个简单的查询,其中通过 sku 编号获取 ChildProdcut
以及针对 IsActive
进行筛选的 PriceTiers
。
Dim ChildProduct = ChildProductRepository.Query.
Where(Function(x) x.Sku = Sku).
Select(Function(x) New With {
.ChildProduct = x,
.PriceTiers = x.PriceTiers.
Where(Function(y) y.IsActive).
OrderBy(Function(y) y.QuantityStart)
}).Select(Function(x) x.ChildProduct).Single
有没有更有效的方法来做到这一点?我完全走在正确的轨道上吗?它确实有效。
我真的不明白的另一件事是为什么这有效?您是否只需要加载一个对象图,EF 就会识别该对象并查看这些集合属于 ChildProduct,即使它们位于匿名类型内部?
另外,格式化长 LINQ 表达式的标准是什么?
I posted a couple of questions about filtering in an eager loading query, and I guess the EF does not support filtering inside of the Include
statement, so I came up with this.
I want to perform a simple query where get a ChildProdcut
by sku number and it PriceTiers
that are filtered for IsActive
.
Dim ChildProduct = ChildProductRepository.Query.
Where(Function(x) x.Sku = Sku).
Select(Function(x) New With {
.ChildProduct = x,
.PriceTiers = x.PriceTiers.
Where(Function(y) y.IsActive).
OrderBy(Function(y) y.QuantityStart)
}).Select(Function(x) x.ChildProduct).Single
Is there a more efficient way of doing this? I am on the right track at all? It does work.
Another thing I really don't understand is why does this work? Do you just have to load an object graph and the EF will pick up on that and see that these collections belong to the ChildProduct even though they are inside of an anonymous type?
Also, what are the standards for formatting a long LINQ expression?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有更有效的方法吗?我完全走在正确的轨道上吗?
不,这就是您在 EF 中执行此操作的方式,是的,您走在正确的轨道上。
我真的不明白的另一件事是为什么它会起作用?
这被认为是有点黑客行为,但它确实有效,因为 EF 分析整个表达式并生成一个查询(它会查看与您刚刚使用
Include
相同,但过滤了PriceTiers
集合)。因此,您将获得已填充(并正确过滤)了PriceTiers
的ChildProducts
。显然,您不需要匿名类的PriceTiers
属性(只需选择x.ChildProduct
即可丢弃它),但将其添加到 LINQ 查询会告诉 EF将join
和额外的where
添加到生成的 SQL 中。因此,ChildProduct
包含您需要的所有内容。Is there a more efficient way of doing this? I am on the right track at all?
Nope, that's about the way you do this in EF and yes, you're on the right track.
Another thing I really don't understand is why does this work?
This is considered to be a bit of a hack, but it works because EF analyzes the whole expression and generates one query (it would look about the same as if you just used
Include
, but with thePriceTiers
collection filtered). As a result, you get yourChildProducts
with thePriceTiers
populated (and correctly filtered). Obviously, you don't need thePriceTiers
property of your anonymous class (you discard it by just selectingx.ChildProduct
), but adding it to the LINQ query tells EF to add thejoin
and the extrawhere
to the generated SQL. As a result, theChildProduct
contains all you need.如果此功能很重要,请创建一个存储过程并将实体框架链接到它。
If this functionality is critcal, create a stored procedure and link entity framework to it.