Created
April 17, 2013 22:42
-
-
Save amiry-jd/5408387 to your computer and use it in GitHub Desktop.
orderby descending in a TransformResults and paging it in RavenDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the documents | |
public class Photo { | |
public string Id { get; set; } | |
public DateTimeOffset CreatedAt { get; set; } | |
} | |
public class Place { | |
public string Id { get; set; } | |
public string Name { get; set; } | |
public DateTimeOffset CreatedAt { get; set; } | |
public IList<string> PhotoIds { get; set; } | |
} | |
/////////////////////////////////////////////////////////////////////////////// | |
// view-model | |
public class PlaceForDisplayListModel { /* some properties same as document */ } | |
public class PhotoModel { /* some properties same as document */ } | |
/////////////////////////////////////////////////////////////////////////////// | |
// the transformer | |
public class PlaceWithCoverPhotoTransfromer | |
: AbstractIndexCreationTask<Place> { | |
public PlaceWithCoverPhotoTransfromer() { | |
Map = places => from place in places | |
select new { place.Name }; | |
TransformResults = (database, places) => | |
from place in places | |
orderby place.CreatedAt descending | |
let cover = place.PhotoIds.Any() ? database.Load<Photo>(place.PhotoIds.First()) : null | |
let coverPhoto = cover == null | |
? null | |
: new { | |
PhotoId = cover.Id, | |
// there are some other properties -not important | |
} | |
select new { | |
Id = place.Id, | |
Name = place.Name, | |
CoverPhoto = coverPhoto | |
// there are some other properties -not important | |
}; | |
} | |
} | |
/////////////////////////////////////////////////////////////////////////////// | |
// the query | |
var temp = _session.Query<Place, PlaceWithCoverPhotoTransfromer>() | |
.Statistics(out stats) | |
// because some complex properties, I have to project as dynamic and cast objects later. | |
.AsProjection<dynamic>() | |
.Skip((query.PageNumber - 1) * query.PageSize) | |
.Take(query.PageSize) | |
.ToArray(); | |
var list = new PlaceForDisplayListModel[temp.Length]; | |
for (var i = 0; i < list.Length; i++) { | |
var item = temp[i]; | |
list[i] = new PlaceForDisplayListModel { | |
// converting RavenDB IDs to int IDs to use in ASP.NET MVC routes. Nothing important | |
Id = ((object)item.Id).ToModelId(), | |
Name = item.Name, | |
CoverPhoto = item.CoverPhoto == null ? null : new PhotoModel { | |
PhotoId = ((object)item.CoverPhoto.PhotoId).ToModelId() | |
// ,some other properties | |
} | |
// ,some other properties | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment