Sobes.tech
Junior — Middle

What are the differences between the include and theninclude methods when working with relationships in ORM?

sobes.tech AI

Answer from AI

The Include method in ORM (e.g., Entity Framework) is used for eager loading of first-level related entities. That is, it allows loading related data of a navigation property along with the main entity.

ThenInclude is used for loading related entities of the second level and beyond, i.e., for nested navigation properties after Include.

Example:

var orders = context.Orders
    .Include(o => o.Customer)           // load related Customer
    .Include(o => o.OrderItems)         // load collection of OrderItems
        .ThenInclude(oi => oi.Product) // for each OrderItem, load Product
    .ToList();

Here, Include loads OrderItems, and ThenInclude loads the related Product.

Thus, Include starts the chain of loading related data, and ThenInclude extends it for nested relations.

What are the differences between the include and… - sobes.tech