Erick Petrucelli
Erick Petrucelli

Reputation: 14872

OrderBy a Many To Many relationship with Entity Sql

I'm trying to better utilize the resources of the Entity Sql in the following scenario: I have a table Book which has a Many-To-Many relationship with the Author table. Each book may have from 0 to N authors. I would like to sort the books by the first author name, ie the first record found in this relationship (or null when no authors are linked to a book).

With T-SQL it can be done without difficulty:

SELECT
    b.*
FROM
    Book AS b
    JOIN BookAuthor AS ba ON b.BookId = ba.BookId
    JOIN Author AS a ON ba.AuthorId = a.AuthorId
ORDER BY
    a.AuthorName;

But I cannot think of how to adapt my code bellow to achieve it. Indeed I don't know how to write something equivalent directly with Entity Sql too.

Entities e = new Entities();
var books = e.Books;
var query = books.Include("Authors");

if (sorting == null)
    query = query.OrderBy("it.Title asc");
else
    query = query.OrderBy("it.Authors.Name asc"); // This isn't it.

return query.Skip(paging.Skip).Take(paging.Take).ToList();

Could someone explain me how to modify my code to generate the Entity Sql for the desired result? Or even explain me how to write by hand a query using CreateQuery<Book>() to achieve it?

EDIT

Just to elucidate, I'll be working with a very large collection of books (around 100k). Sorting them in memory would be very impactful on the performance. I wish the answers would focus on how to generate the desired ordering using Entity Sql, so the orderby will happens on the database.

Upvotes: 1

Views: 2371

Answers (2)

Michael Edenfield
Michael Edenfield

Reputation: 28338

The OrderBy method expects you to give it a lambda expression (well, actually a Func delegate, but most people would use lambdas to make them) that can be run to select the field to sort by. Also, OrderBy always orders ascending; if you want descending order there is an OrderByDescending method.

var query = books
  .Include("Authors")
  .OrderBy(book => book.Authors.Any()
    ? book.Authors.FirstOrDefault().Name
    : string.Empty);

This is basically telling the OrderBy method: "for each book in the sequence, if there are any authors, select the first one's name as my sort key; otherwise, select the empty string. Then return me the books sorted by the sort key."

You could put anything in place of the string.Empty, including for example book.Title or any other property of the book to use in place of the last name for sorting.

EDIT from comments:

As long as the sorting behavior you ask for isn't too complex, the Entity Framework's query provider can usually figure out how to turn it into SQL. It will try really, really hard to do that, and if it can't you'll get a query error. The only time the sorting would be done in client-side objects is if you forced the query to run (e.g. .AsEnumerable()) before the OrderBy was called.

In this case, the EF outputs a select statement that includes the following calculated field:

    CASE WHEN ( EXISTS (SELECT 
        1 AS [C1]
        FROM [dbo].[BookAuthor] AS [Extent4]
        WHERE [Extent1].[Id] = [Extent4].[Books_Id]
    )) THEN [Limit1].[Name] ELSE @p__linq__0 END AS [C1], 

Then orders by that.

@p__linq__0 is a parameter, passed in as string.Empty, so you can see it converted the lambda expression into SQL pretty directly. Extent and Limit are just aliases used in the generated SQL for the joined tables etc. Extent1 is [Books] and Limit1 is:

SELECT TOP (1) -- Field list goes here.
FROM  [dbo].[BookAuthor] AS [Extent2]
INNER JOIN [dbo].[Authors] AS [Extent3] ON [Extent3].[Id] = [Extent2].[Authors_Id]
WHERE [Extent1].[Id] = [Extent2].[Books_Id] 

Upvotes: 3

ctorx
ctorx

Reputation: 6941

If you don't care where the sorting is happening (i.e. SQL vs In Code), you can retrieve your result set, and sort it using your own sorting code after the query results have been returned. In my experience, getting specialized sorting like this to work with Entity Framework can be very difficult, frustrating and time consuming.

Upvotes: 0

Related Questions