Filtering EntityFramework Poco LoadProperty

In POCO, I use explicit loading via LoadProperty to load data. I need to filter and sort data from a property that has loaded and return the main object.

Let's say there is an album class whose photos are a collection. I need to return the album object from DAL. So the code will 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 code above, I need to return only the last 10 photos, I can not filter or sort the collection of photos, as shown in the code. What is the best way to handle this? Even if we create a new object, how do I copy all the album information into a new album?

+4
source share
2 answers

As already mentioned, if you want to have some kind of custom loading of navigation properties (like filtering or ordering), you can't use the built-in explicit search / delayed loading methods (like Load). Since you are using POCOs, you have only two options:

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 result in an anonymous type, which may not always be desirable, in this case there is another way:

Two tracked requests:

 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); } 
+3
source

It looks like you are trying to change the definition of an entity that you get from the Entity Framework. If you want only 10 photos to be filled for this album, you should consider changing or expanding the model, and not try to make this design at the time of the request.

A good solution can be as simple as adding an object property for the filtering you mentioned and returning 10 results.

0
source

All Articles