
إزاي تحل الـ N+1 في EF Core من غير Include لكل حاجة؟ الـ projections والـ split queries
- كاتب موثّق
- EF Core 10
محتويات المقال
Include، والـ log نزل لـ command واحد، ومعاه warning محدش بيقراه. الـ command ده رجّع 1,500 row فيهم 17 عمود، وخلّى 730 entity متتبّعين، عشان يبني 50 summary في كل واحد 4 قيم بس.
الفكرة الغلط الشائعة
Include ناقص. اعمل Include لكل navigation الكود بيلمسه، وكده الـ data access اتصلّح.
Include فعلًا بيشيل الرحلات الزيادة، والـ performance guide بتاع Microsoft نفسه بيقول حمّل الـ related entities بـ eager loading لما تبقى عارف إنك هتحتاجها. والرقم اللي أغلب الناس بتبص عليه، عدد الـ queries في الـ request، بينزل من 111 لـ 1. وعلى داتابيز الـ development اللي فيها 3 orders، الـ query الجديدة بتطلع سريعة.
اللي بيحصل فعلًا
الـ N+1 بييجي منين؟
foreach بيعمل query أو بينادي Load() لكل item بيعمل نفس الحكاية. والـ docs بتاعة Microsoft بتحذّر إن الـ lazy loading بيخلّي الـ N+1 سهل جدًا يحصل، وبتنصح تتجنبه.
الـ Include بيجيب entities، مش إجابات
Include بيقول للـ EF Core يجيب entities كاملة لكل navigation: كل عمود متعمله mapping، ومتتبّع بشكل افتراضي. وصفحة اللستة كانت محتاجة رقم الـ order واسم العميل والـ total وعدد الـ payments. والـ query اللي فيها Include في التجربة رجّعت 17 عمود، منهم وصف للـ product طوله 500 حرف الصفحة عمرها ما بتعرضه، وسابت 730 entity في الـ change tracker.
الـ 2 collections بيضاعفوا الـ rows
MultipleCollectionIncludeWarning كل ما query تحمّل أكتر من collection من غير ما يكون فيه splitting behavior متظبط.
الـ projection بتسأل عن الإجابة نفسها
Select بيوصف النتيجة بدل الـ entities. والـ EF Core بيترجم الشكل كله لـ SQL، ومعاه Sum و Count على الـ collections، فالداتابيز هي اللي بتحسب الـ totals وبترجّع row واحد لكل order. وفي التجربة، الـ query اللي فيها projection رجّعت 50 row فيهم 4 أعمدة ومفيش أي حاجة اتتبّعت. والـ Include مالوش لازمة هنا: في التجربة، إضافته لـ query بتعمل projection لـ DTO ماغيّرتش أي حاجة في الـ SQL.
الحل: اعمل projection للقراية
using Microsoft.EntityFrameworkCore;public sealed class OrderSummaries(ShopDb db){ public async Task<List<OrderSummary>> ListAsync( DateTime since, CancellationToken ct) { // One query instead of 111, but whole entities from five tables var orders = await db.Orders .Include(o => o.Customer) .Include(o => o.Lines).ThenInclude(l => l.Product) .Include(o => o.Payments) .Where(o => o.PlacedAt >= since) .ToListAsync(ct); // tested: 1,500 rows, 17 columns, 730 tracked return orders.Select(o => new OrderSummary(o.Id, o.Customer.Name, o.Lines.Sum(l => l.Quantity * l.UnitPrice), o.Payments.Count)).ToList(); }}using Microsoft.EntityFrameworkCore;public sealed class OrderSummaries(ShopDb db){ public Task<List<OrderSummary>> ListAsync( DateTime since, CancellationToken ct) => db.Orders .Where(o => o.PlacedAt >= since) // Sum and Count run in SQL: one row per order, four columns .Select(o => new OrderSummary( o.Id, o.Customer.Name, o.Lines.Sum(l => l.Quantity * l.UnitPrice), o.Payments.Count)) .ToListAsync(ct); // tested: 50 rows, nothing tracked}لما تحتاج الـ collections نفسها
using Microsoft.EntityFrameworkCore;public sealed class OrderDetailsQuery(ShopDb db){ public Task<OrderDetails> GetAsync(int id, CancellationToken ct) => db.Orders.Where(o => o.Id == id) .Select(o => new OrderDetails(o.Id, o.Customer.Name, o.Lines.Select(l => new LineDto(l.Product.Name, l.Quantity)) .ToList(), o.Payments.Select(p => new PaymentDto(p.Amount, p.PaidAt)) .ToList())) // One SQL query per collection instead of lines × payments rows .AsSplitQuery() .SingleAsync(ct);}AsSplitQuery على اللستة الأصلية بالـ 4 Include، الـ 1,500 row نزلوا لـ 700 على 3 commands، بس فضل الـ 730 entity متتبّعين.
Include لكل حاجة | |||
Include + AsSplitQuery | |||
Select |
تطبقها إزاي في مشروعك
عِد الـ commands في كل request شغّل الـ command logging ودوّر على شكلين: نفس الـ SELECTمتكرر بـ key مختلف (N+1)، و statement واحدة فيها كذاLEFT JOINعلى collections (explosion).اقفل الـ lazy loading في مسارات القراية شيل UseLazyLoadingProxies، أو على الأقل ابعد الـ entities اللي عليها proxies عن الـ mappers والـ serializers، لأن لمس الـ navigations هناك مش باين.اعمل projection في الـ read endpoints اعمل Selectللـ DTO اللي الـ response محتاجه، وسيبCountوSumوباقي الـ aggregates تشتغل في الـ SQL. وشيلIncludeمن الـ queries اللي بتعمل projection لـ DTO، مالوش أي تأثير هناك.اعمل split بس مكان ما الـ collections بتتضاعف استخدم AsSplitQueryعلى الـ queries اللي بتحمّل 2 collections أو أكتر، أو اظبطUseQuerySplittingBehaviorعلى مستوى التطبيق واستثني بـAsSingleQuery.
الخلاصة
الـ N+1 مشكلة رحلات للداتابيز: داتا مرتبطة بتتحمّل لكل row عن طريق الـ lazy loading أو Load()أو queries جوه loops.الـ Includeبيحل الرحلات بس بيجيب entities كاملة ومتتبّعة، و 2 collections بيضاعفوا الـ rows: 1,500 لـ 50 order في التجربة.في القراية، اعمل projection للي الـ response محتاجه بالظبط، فالـ aggregates تشتغل في الداتابيز ومفيش حاجة تتتبّع. الـ Includeمالوش أي تأثير في query بتعمل projection لـ DTO، فماتجمعش بينهم.لما تحتاج كذا collection، استخدم AsSplitQueryواقبل الـ trade-offs بتاعته: رحلات زيادة ومفيش snapshot واحدة.
التعليقات (0)