依赖实体上的Where条件导致实体框架性能缓慢

本文关键字:实体 框架 缓慢 性能 条件 Where 依赖 | 更新日期: 2023-09-27 18:00:09

context.PaymentEntity.Include("UserPaymentEntity")
                     .Include("UserPaymentEntity.RefundEntity")
                     .Include("RequestEntity")
                     .Include("RequestEntity.PremiumEntity")
                     .Include("RequestEntity.PremiumEntity.TypeEntity")
                     .Include("RequestEntity.PremiumEntity.TypeEntity.CategoryEntity")
                     .Include("RequestEntity.PremiumEntity.TypeEntity.CategoryEntity.CategoryTypeEntity")
                     .Where(x => x.RequestKey != null && 
                                 x.RequestEntity.UserKey == usrKey && 
                                 '03/01/2016' <= x.ReceivedDate && 
                                 x.ReceivedDate <= '03/31/2016');

这种情况会降低性能。因为它正在从依赖实体访问userKey。

我该如何改进?这些表在每个表中有50万到100万条记录。

感谢

依赖实体上的Where条件导致实体框架性能缓慢

1(如果可能的话,进行小查询并在内存中加入它们。

2( 您的查询将不起作用-您需要日期和时间为"2016年3月31日"的DbFunction

3( 在UserPaymentEntity中,您需要CategoryTypeEntity实体,为什么不在UserPaymentEntity.CategoryTypeEntity中添加导航属性?这将减少连接地狱。

4( 当EF遇到困难,无法达到您的性能要求时,请使用Views。

5( 使用nameof(UserPaymentEntity)而不是字符串"UserPaymentEntity",这对于重构来说更干净。

6( 这包括:.Include("RequestEntity.PremiumEntity.TypeEntity.CategoryEntity.CategoryTypeEntity")

将自动包括整个导航路径"RequestEntity""RequestEntity.PremiumEntity",等。你不必把它们都写出来!

7( 如果您只想读取数据,请使用:

this.Configuration.AutoDetectChangesEnabled = false;

或使用AsNoTracking 获取数据

8( 也许您可以将查询逻辑划分为页面,并使用Take和Skip。

9( 对固定数据使用二级现金。https://efcache.codeplex.com/

过去,我曾将SPROC用于大型查询,发现对SQL的有限控制是一种简单得多的方法。我并不是说EF方法不好,但它可能值得考虑SPROC,这样你就可以利用临时表等来进一步过滤你的数据集。