简体   繁体   中英

Entity Framework query ignoring my orderby

I have myself this SQL query

SELECT db_accounts_last_contacts . id , dbe_accounts_last_contacts . last_contact_date , db_accounts_last_contacts . description , db_accounts_last_contacts . follow_up_date , db_accounts_last_contacts . spoke_to_person_id , db_accounts_last_contacts . account_id FROM db_accounts_last_contacts , db_companies WHERE db_companies . id = db_accounts_last_contacts . account_id ORDER BY db_accounts_last_contacts . last_contact_date DESC

Which returns my results ordered by last_contact_date.

Now I have my Entity framework query

var query = (from c in context.accounts_companies
             select new AccountSearchResultModel()
             {
                 LastContacted = (from calc in context.communique_accounts_last_contacts
                                  where calc.account_id == companyId
                                  orderby calc.last_contact_date descending
                                  select calc.last_contact_date).FirstOrDefault()
            });

However when I go ahead and do my ToList on it, my results are never ordered Here is my table un-ordered 在此处输入图片说明

Here is my list ordered using the SQL query 在此处输入图片说明

Why isn't my entity framework query not picking up my orderby? Or if it is why am I always pulling out the first one?

You need to choose a Property to sort by and pass it as a lambda expression to OrderByDescending like this:

.OrderByDescending(x => x.calc.last_contact_date);

I hope this helps.

Linq Orderby Descending Query

Sorry for the late answer,

What I had to do in the end was create a view and import it via the EDMX file and then use that to pull out my results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM