Union order in Linq to Entities

瘦欲@ 提交于 2019-12-22 06:56:27

问题


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!


回答1:


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



回答2:


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

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


来源:https://stackoverflow.com/questions/5870599/union-order-in-linq-to-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!