I have a look at definitions and examples of EF Include()
method but unfortunately, there is not a proper explanations for my question "What is Entity Framework Include() and when to use it?".
Here is an example usage. What is the general purpose of it and why / when should I use it?
using (var context = new MyContext())
{
var list = context.Customers
.Include(c => c.Invoices)
.ToList();
foreach (var customer in list)
{
Console.WriteLine("Customer Name: {0}", customer.Name);
foreach (var customerInvoice in customer.Invoices)
{
Console.WriteLine("\tInvoice Date: {0}", customerInvoice.Date);
}
}
}
In your case I assume "Customers" and "Invoices" are two separate tables.
Let's say you got one customer :
var customer = context.Customers.FirstOrDefault();
If you try to reach the invoices for that customer :
customer.Invoices
What will happens? It will depends your ORM configuration. There are 2 modes.
Lazy loading With that mode, which is the default one I think, you will have a first call to the database to retrieve the customer (but only the customer) then a second call to the database to retrieve the invoices for that customer. But that second call will only happens when you will try to reach the invoices.
Eager loading If you don't want to have multiple database calls and you want to get all data in one call you can disable the lazy loading. But if you get the customer the same way I showed above you will not get the invoices (you will get "null" instead). The "Include" allow EF to know you want to retrieve the customer AND the invoices in one database call:
var customer = context.Customers.Includes(c => c.Invoices).FirstOrDefault();
And when you will try to get the invoices for that customer, everything will be already in memory so no additional database call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With