Linq to Entities: Union Order

c# entity-framework linq linq-to-entities

Question

I have a problem with EDM model Union select. I have unique IDs for each entry in my database. Id list, for instance: 1, 2, 3, 4, 5, 6, 7, 8, 9.

For instance, I need to choose record number 6, two records before to it, and two records after it. It should read 4,5,6,7,8 in the chosen result.

This is how I created 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 descending
                  select m).Take(3).Skip(0);
        return (p1.Union(p2));
    }

However, the sequence is different from the example.

I appreciate the support.

1
5
5/3/2011 3:11:27 PM

Accepted Answer

You cannot ensure order with it because of the later Union. When you get back, you should:

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

Update

With further knowledge of the problems, I believe this will solve the problem:

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));
}
3
5/3/2011 3:03:25 PM

Popular Answer

No ordering may be taken for granted. If you want objects to be ordered, you must always have an OrderBy.

return p1.Union(p2).OrderBy(p=> p.id);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow