What is explicit loading?
Explicit loading is a technique used in LINQ to load related entities or data explicitly when needed. It allows you to control the loading behavior and manually fetch specific related entities or collections.
Here's an example that illustrates explicit loading in LINQ:
Consider the same 'Customer' and 'Order' entities as mentioned before:
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public ICollection Orders { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public decimal TotalAmount { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
To explicitly load the associated orders for a specific customer, you can use the Load method provided by LINQ to SQL:
var customer = dbContext.Customers.FirstOrDefault(c => c.CustomerId == customerId);
dbContext.Entry(customer).Collection(c => c.Orders).Load();
foreach (var order in customer.Orders)
{
Console.WriteLine($"Order: {order.OrderId}, Date: {order.OrderDate}, Amount: {order.TotalAmount}");
}
In this example, the 'Load' method is used to explicitly load the 'Orders' collection for the 'customer' entity. The 'Entry' method retrieves the 'EntityEntry' object associated with the customer, and the 'Collection' method specifies the navigation property 'c.Orders' that should be loaded.
By using explicit loading, you have control over when and how related entities are loaded. It allows you to fetch related data on-demand and avoid the automatic loading behavior of lazy loading.
Explicit loading is particularly useful when you have scenarios where you want to selectively load related data for specific entities, reducing unnecessary database queries and optimizing performance.
It's important to note that explicit loading requires an active database connection and the availability of related data in the database. You should also be cautious about the potential performance implications, especially if you need to load related data for multiple entities, as it may result in the N+1 problem, where separate queries are executed for each related entity.
Overall, explicit loading in LINQ provides fine-grained control over loading related entities, allowing you to manually fetch specific data as needed. It helps optimize performance and avoid unnecessary data retrieval, particularly in scenarios where lazy loading may not be suitable or efficient.