Why did Entity Framework Core include related tables without me using Include() in my query?

1.2k Views Asked by At

I'm using Entity Framework Core version 5 and this is my table:

public class BusinessTransaction
{
    public Guid Id { get; set; }
    public Guid BusinessId { get; set; }

    public int Amount { get; set; }
    public bool IsPay { get; set; }
    public DateTime Date { get; set; }

    public string Title { get; set; }
    public long Time { get; set; }
    public string TrackingCode { get; set; }

    [ForeignKey(nameof(BusinessId))]
    public Businesses.Business Business { get; set; } 
}

When I want to get data, EF Core seems to include the Business table without me using an Include(). This is my query:

public async Task<List<BusinessTransaction>> GetTransactionByBusienssId(Guid id, int skip = 0, int take = 10)
{
    var query = DbContext.BusinessTransactions
                         .Where(b => b.BusinessId == id)
                         .OrderByDescending(b => b.Date)
                         .Skip(skip)
                         .Take(take);

    return await query.ToListAsync();
}

This is query that executes in SQL Server (reformatted for readability):

DECLARE @__id_0 uniqueIdentifier = '2af03a2e-17b6-4708-ceee-08da1fc18b20';
DECLARE @__p_1 int = 0;
DECLARE @__p_2 int = 10;
    
SELECT
    [b].[Id],
    [b].[Amount],
    [b].[BusinessId],
    [b].[Date],
    [b].[IsPay],
    [b].[Time],
    [b].[Title],
    [b].[TrackingCode]
FROM
    [BusinessTransactions] AS [b]
WHERE
    [b].[BusinessId] = @__id_0
ORDER BY
    [b].[Date] DESC
OFFSET
    @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY;

How can I execute query without including any related table?

1

There are 1 best solutions below

0
VoidA313 On

Your question is related to Eager loading, Please read below concepts of eager vs lazy. When you call include() it is eager loading where EF calls all related entities, I believe what you look for is lazy loading where EF won't load related entities (navigation props) until you explicitly call them. https://www.entityframeworktutorial.net/eager-loading-in-entity-framework.aspx https://www.entityframeworktutorial.net/lazyloading-in-entity-framework.aspx

Good luck.