EntityFramework Poco LoadProperty Filtering
In POCO, I am using explicit Loading via LoadProperty to load the data. I need to filter and sort the data from the property that's loaded and return the main object.
Say, there is an album class of which photos is a collection. I need to return the "album" object from the DAL. So, the code would be
public Album GetPhotos()
{
using (var context = new Entities())
{
//....code for loading album....
context.LoadProperty(album, "Photos");
//I need to return ONLY the latest 10 photos
// album.Photos = album.Photos.OrderByDescending(a=>a.CreateDate).Take(10); //DOES NOT WORK
return album;
}
}
Now in the above code, I need to return only latest 10 photos, I cannot filter or sort the photos collection as shown in the code. What's the best way to handle this? Even if we create a new object, how would we copy all the album information to 开发者_StackOverflowthe new album?
Like it's mentioned, if you want to have any sort of customized navigation property loading (e.g. filtering or ordering) then you cannot use the built in explicit eager/deferred loading methods (e.g. Load). Since you are using POCOs, you only have 2 options to go for:
Filtered Projection with Anonymous Types:
var album = context.Albums.Where(a => a.AlbumId == 1).Select(a => new
{
a,
Photos = a.Photos.OrderByDescending(alb => alb.CreateDate).Take(10)
});
This will returns an anonymous type Which might not always be desirable, in that case there is yet another way:
Two Tracked Queries:
Album album = context.Albums.Where(a => a.AlbumId == 1).Single();
List<Photo> photos = context.Photos
.Where(p => p.AlbumId == 1)
.OrderByDescending(a => a.CreateDate).Take(10)
.ToList();
foreach (Photo photo in photos)
{
album.Photos.Add(photo);
}
It seems like what you're trying to do is alter the definition of an entity which you are getting from Entity Framework. If you only want 10 photos to be populated for a given album, you ought to consider altering or extending the model, rather than trying to make that construction during query time.
A good solution might be as simple as adding a property on the object to do the filtering you've mentioned and return 10 results.
精彩评论