Sachin
Sachin

Reputation: 2148

How to OrderBy reference table column in Entity framework

I have 2 tables with reference like : Order & Product
I am using EF. Now I have a page where it shows like this :

OrderNo | OrderDate | ProductName | Price


There is a foreign key of Product table (ProductID) and I am showing o.Product.ProductName
Now I want to OrderBy the list by Product Name which is in Product Table.
How can I do this?
FYI : ProductID in Order Table is Nullable

Thanks in advance

Upvotes: 1

Views: 2577

Answers (2)

Oleg Polezky
Oleg Polezky

Reputation: 1132

In more complex case the code could look like this

.OrderByDescending(x => 
    !x.CONTACTPERSON.Any() 
        ? 0 
        : x.CONTACTPERSON.Max(
            y => !y.INTERACTIONENTRY.Any()
            ? 0
            : y.INTERACTIONENTRY.Max(z => z.InteractionEntryID)) 
    )

Upvotes: 1

Raphaël Althaus
Raphaël Althaus

Reputation: 60503

Well it seems you have a navigation property Product in Order class

so you could do

.OrderBy(o => (o.Product == null) ? string.Empty : o.Product.ProductName)

you could also do in two pass

.OrderByDescending(o => o.Product == null) //or OrderBy, depending if you want null first or last
.ThenBy(o => (o.Product == null) ? string.Empty : o.Product.ProductName); 

Upvotes: 4

Related Questions