简体   繁体   English

每次迭代的实体框架查询

[英]Entity framework query per iteration

When using EntityFramework very often this error occurs: developer forgets call method like Include(x => x.Author) on DbSet, and then in foreach cycle he call blog.Author . 当经常使用EntityFramework时,会发生此错误:开发人员忘记了Include(x => x.Author)上的Include(x => x.Author)类的调用方法,然后在foreach周期中他调用了blog.Author As result, in every cycle iteration EF do database query, which works very slow. 结果,在每个循环迭代中,EF都会进行数据库查询,这非常慢。

How detect places in code like this? 如何在这样的代码中检测位置? May be static code analyzer or something like it? 可能是静态代码分析器还是类似的东西?

It would be ideal to search "bad places" in every continuous integration build. 在每个连续的集成版本中搜索“坏地方”都是理想的。 If it possible :) 如果可能的话:)

I am afraid I don't have a silver bullet for you but having experienced similar frustrations on a not insignificant codebase I thought I would put in my 2 cents. 恐怕我对您没有灵丹妙药,但是在一个无关紧要的代码库上遇到了类似的挫折,我以为我会投入2美分。 Here is how I alleviated the problem. 这是我缓解问题的方法。 This required a lot of work, and maybe it could be done on any new code and whenever a bug is fixed... 这需要大量的工作,也许可以在任何新代码上完成,并且只要有错误修复就可以完成。

I suggest you divide your entities into aggregates that are usually required together. 我建议您将实体分为通常需要一起使用的汇总。 Then you create repositories that work with these aggregates as a group. 然后,您可以创建将这些聚合作为一个组使用的存储库。 As an example you would always get Orders by querying the Customer but if you needed the order item details for the Product, you would have to go query that Product by the ProductId on the OrderLineItem. 例如,您始终可以通过查询客户来获取订单,但是如果您需要该产品的订单项详细信息,则必须通过OrderLineItem上的ProductId来查询该产品。

The basic idea is that you are always working with aggregate roots. 基本思想是您始终使用聚合根。 This is a concept from Domain Driven Design, which is a pretty huge topic. 这是领域驱动设计的概念,这是一个非常大的主题。 Here is a primer: https://lostechies.com/jimmybogard/2010/02/04/strengthening-your-domain-a-primer/ 这是入门读物: https : //lostechies.com/jimmybogard/2010/02/04/strengthening-your-domain-a-primer/

http://dddcommunity.org/ http://dddcommunity.org/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM