Matthew Verstraete
Matthew Verstraete

Reputation: 6781

LINQ to Entities result not being sorted right

I have a LINQ to Entities query that is supposed to output data based on a DateTime field in Ascending order. But, it is not outputting the data in any particular order and I can't figure out the reason.

I have done a basic SELECT statement to the DB and get the data back in the proper order. It appears that the OrderBy command of the LINQ query is just being ignored. How can I see SQL being generated?

I have tried LINQPad but it keeps giving a BS error about context not being updated even though an UPDATE-DATABASE command says no pending changes Or if I can not see what is being generated what is the best way to be debugging this?

db.Releases
.Where(r => r.SectionID == model.ID)
.Include("Platform")
.Include("Region")
.Include("Publisher")
.OrderBy(r => r.DateReleased.HasValue)
.Select(r => new ReleaseInfoVM()
{
    ReleaseName = r.Name,
    Platform = r.Platform.Name,
    Publisher =r.Publisher.Name,
    Region = r.Region.Name,
    ISBN = r.ISBN,
    DateReleased = r.DateReleased,
    EstimatedReleaseDate = r.EstimatedReleaseDate
}).ToList();

Upvotes: 0

Views: 65

Answers (1)

Mark Miller
Mark Miller

Reputation: 7447

.HasValue returns a boolean. True if the property is not null. That won't work. Instead, try:

.OrderBy(r => r.DateReleased)

As @user2864740 pointed out in the comments, to ensure that the null values go to the end of the list, try:

.OrderBy(r => r.DateRelease ?? DateTime.Max)

Upvotes: 3

Related Questions