问题
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