The both query are retrieving the related data just first query by using Eager Loading (and yes Eager loading is achieved by use of the Include
method as you guessed) and the second query by using Lazy loading which is by default. But since your query will only returns EmailAddresses
because of the Select()
and SelectMany()
operations the Include()
method doesn't change the behavior. To see when Include()
method is matter in your example read the following lines that I will prove it in one example:
To know some difference between this two kind of loading related entities Eager loading is typically more efficient when you need the related data for all retrieved rows of the primary table. And also when relations are not too much, eager loading will be good practice to reduce further queries on server. But when you know that you will not need a property instantly then lazy loading maybe a good choice. And also eager loading is a good choice in a situation where your db context would be disposed and lazy loading could not take place anymore.
To prove that one is Lazy Loading and one is Eager Loading consider the following code:
public List<Person> GetEmailAddresses()
{
using (yourEntities awlt = new yourEntities())
{
var query = awlt.People
.Where(p => p.LastName.Equals(lastName));
return query.ToList();
}
}
After calling this method, You cannot load the related entity lazily because the db is disposed. To prove try this:
var query = GetEmailAddresses();
foreach (var item in query.SelectMany(a => a.EmailAddresses).Select(a => a.EmailAddress1))
{
MessageBox.Show(item);
}
And you will get this error:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
But if you change the GetEmailAddresses
to use Eager Loading like this:
public List<Person> GetEmailAddresses()
{
using (yourEntities awlt = new yourEntities())
{
var query = awlt.People.Include("EmailAddresses")
.Where(p => p.LastName.Equals(lastName));
return query.ToList();
}
}
Then the below code should works fine:
var query = GetEmailAddresses();
foreach (var item in query.SelectMany(a => a.EmailAddresses).Select(a => a.EmailAddress1))
{
MessageBox.Show(item);
}
So in a situation where your db context would be disposed the Eager Loading would be a better choice.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…