Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7595091
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T21:35:07+00:00 2026-05-30T21:35:07+00:00

I’m trying to better utilize the resources of the Entity Sql in the following

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T21:35:08+00:00Added an answer on May 30, 2026 at 9:35 pm

    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] 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I want to count how many characters a certain string has in PHP, but
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a text area in my form which accepts all possible characters from
I am trying to loop through a bunch of documents I have to put
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.