http://foreverframe.net/when-use-include-with-entity-framework/
class Program
{
static void Main(string[] args)
{
using (var context = new BookStoreContext())
{
var author = context.Authors
.Include(a => a.Books)
.FirstOrDefault();
foreach (var book in author.Books)
Console.WriteLine(book.Title);
}
Console.ReadLine();
}
}
|
Making JOIN without Include method
Frankly, I would say that the following solution should be your default way of dealing with IQuerable. Let’s modify our Program class one, last time:
class Program
{
static void Main(string[] args)
{
using (var context = new BookStoreContext())
{
var author = context.Authors
.Select(a => new AuthorReadModel
{
FirstName = a.FirstName,
LastName = a.LastName,
BookTitles = a.Books
.AsQueryable()
.Select(b => b.Title)
.ToList()
})
.FirstOrDefault();
foreach (var title in author.BookTitles)
Console.WriteLine(title);
}
Console.ReadLine();
}
}
|
In this case, we created a dedicated ReadModel for all needed data, and we specified all “mappings” inside the Select method. This one tells EF exactly what we need, so it does not need yet another help as Include method. Let’s run the following code and inspect the query:
SELECT
[Project1].[Id] AS [Id],
[Project1].[FirstName] AS [FirstName],
[Project1].[LastName] AS [LastName],
[Project1].[C1] AS [C1],
[Project1].[Title] AS [Title]
FROM ( SELECT
[Limit1].[Id] AS [Id],
[Limit1].[FirstName] AS [FirstName],
[Limit1].[LastName] AS [LastName],
[Extent2].[Title] AS [Title],
CASE WHEN ([Extent2].[AuthorId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
FROM (SELECT TOP (1) .[Id] AS [Id], .[FirstName] AS [FirstName], .[LastName] AS [LastName]
FROM [dbo].[Authors] AS ) AS [Limit1]
LEFT OUTER JOIN [dbo].[Books] AS [Extent2] ON [Limit1].[Id] = [Extent2].[AuthorId]
) AS [Project1]
ORDER BY [Project1].[Id] ASC, [Project1].[C1] ASC
|
No comments:
Post a Comment