Entity Framework Eagerly Loading Related

Tarique Iqbal 0 Reputation points
2025-03-05T06:43:34.1466667+00:00

Hi there,

Which of the following two is better for performance?

  1. Requisition req = _context.Requisitions.Where(r => r.Id == id).Include(r=> r.Beneficiary).Include(r=> r.RequisitionStatus).FirstOrDefault();
  2. Requisition req = _context.Requisitions.Include(r => r.Beneficiary).Include(r => r.RequisitionStatus).FirstOrDefault(r => r.Id == id);

Thanks in advance

Tarique Iqbal

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,333 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Hongrui Yu-MSFT 4,840 Reputation points Microsoft External Staff
    2025-03-05T07:47:24.8566667+00:00

    Hi, @Tarique Iqbal. Welcome to Microsoft Q&A. 

    Usually the second method performs better. But the performance difference between the two depends on the specific situation. You could print out the time they take to execute SQL queries for comparison.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("...");
    	//Print the executed SQL
        optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);
    }
    

    You could also use Stopwatch to calculate the total time from executing this statement to getting the data.

    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();
    Requisition req1 = _context.Requisitions.Where(r => r.Id == id).Include(r => r.Beneficiary).Include(r => r.RequisitionStatus).FirstOrDefault();
    stopwatch.Stop();
    Console.WriteLine("Method 1: {0} ms", stopwatch.ElapsedMilliseconds);
    stopwatch.Reset();
    stopwatch.Start();
    Requisition req2 = _context.Requisitions.Include(r => r.Beneficiary).Include(r => r.RequisitionStatus).FirstOrDefault(r => r.Id == id);
    stopwatch.Stop();
    Console.WriteLine("Method 2: {0} ms", stopwatch.ElapsedMilliseconds);
    

    In my test, the second method usually takes 2ms to execute SQL on the same database, and the first method usually takes 60ms.

    enter image description here


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.