Ray
Ray

Reputation: 4929

How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?

I wrote the following code for one of my controller actions in an ASP.NET Core application and I want to know how many times the database was called. There are two LINQ statements, one that fetches the data and another that sorts the children. How does one confirm the number of database calls? I'm using the localdb that gets created by default in a Code First .NET Core application.

    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var giftCard = await _context.GiftCards.Include(g=>g.Transactions).SingleOrDefaultAsync(m => m.Id == id);                   
        if (giftCard == null)
        {
            return NotFound();
        }
        giftCard.Transactions = giftCard.Transactions.OrderBy(t => t.TransactionDate).ToList();
        return View(giftCard);
    }

Upvotes: 2

Views: 146

Answers (1)

Ganesh
Ganesh

Reputation: 46

Linq allows developers to build a query, which is executed once the full query is built. You can build a query using multiple expressions without making a single call to the database. Linq will delay the call until the last possible moment.

In your case, the statement if (giftCard == null) explicitly asks for the object. Therefore, a database call will be made to fetch the requested GiftCard. Secondly, The OrderBy operation will be performed on the transactions that are already in memory (due to Include(g=>g.Transactions)). So, no database calls here.

Ultimately, your whole code will make only a single database call.

Upvotes: 2

Related Questions