Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union order in Linq to Entities

I have a problem with EDM model Union select. I have the records in db with uniqe Ids. For example id list: 1, 2, 3, 4, 5, 6, 7, 8, 9

I need to select, for example, record #6 and 2 records before #6 and 2 records past #6. In select result it should be 4,5,6,7,8

I made this next way:

public IQueryable<photos> GetNextPrev(Int64 photoid, string userlogin)
    {
        var p1 = (from m in db.photos
                 where m.id < photoid && m.userlogin == userlogin
                 orderby m.id descending
                 select m).Take(2).Skip(0);
        var p2 = (from m in db.photos
                  where m.id >= photoid && m.userlogin == userlogin
                  orderby m.id descending
                  select m).Take(3).Skip(0);
        return (p1.Union(p2));
    }

But the ordering is not like in the example...

Thanks for the help!

like image 879
Evgeniy Labunskiy Avatar asked May 03 '11 13:05

Evgeniy Labunskiy


Video Answer


2 Answers

It's because of the latter Union, you cannot guarantee order with it. You want to do this on your return:

return (p1.Union(p2).OrderByDescending(m => m.id));

Update

With further understanding of the issues, I think this will take care of it:

public IQueryable<photos> GetNextPrev(Int64 photoid, string userlogin)
{
    var p1 = (from m in db.photos
             where m.id < photoid && m.userlogin == userlogin
             orderby m.id descending
             select m).Take(2).Skip(0);
    var p2 = (from m in db.photos
              where m.id >= photoid && m.userlogin == userlogin
              orderby m.id 
              select m).Take(3).Skip(0);
    return (p1.Union(p2).OrderBy(m => m.id));
}
like image 175
Adriano Carneiro Avatar answered Oct 18 '22 18:10

Adriano Carneiro


You can't assume any ordering. You always need an OrderBy if you want things ordered.

return p1.Union(p2).OrderBy(p=> p.id);
like image 36
Ralph Shillington Avatar answered Oct 18 '22 20:10

Ralph Shillington