开发者

Union order in Linq to Entities

开发者 https://www.devze.com 2023-03-02 03:56 出处:网络
I have a problem with EDM model Union select. I have the records in db开发者_如何学C with uniqe Ids. For example id list:

I have a problem with EDM model Union select. I have the records in db开发者_如何学C 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!


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));
}


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

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

精彩评论

暂无评论...
验证码 换一张
取 消