简体   繁体   中英

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 . As result, in every cycle iteration EF do database query, which works very slow.

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. 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.

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/

http://dddcommunity.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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