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