Q:

EF Lambda Query - calculation for each item?

I am getting a collection of items using a service.  I want to calculate distance from a geography coordinate for each item in the results but I don't know how to add that to the existing service query using lambda.  
This is how I'm getting the data:
IEnumerable<Listing> items = await _listingService.Query(x => x.CategoryID 
        == model.CategoryID || keys.Any(c => c == x.CategoryID))
                    .Include(x => x.ListingPictures)
                    .Include(x => x.Category)
                    .SelectAsync();

This is how I would get the distance using LINQ but this is using the items collection after the above statement is run:
double lat = 41.2;
double lon = -71.01;
DbGeography point = DbGeography.FromText(String.Format(CultureInfo.InvariantCulture, "POINT({0} {1})", lon, lat));

List<Listing> items1 = new List<Listing>(from g in items
                          let distance = g.Geolocation.Distance(point)
                          orderby distance
                          select new Listing()
                             {
                                 ID = g.ID,                               
                                 CategoryID = g.CategoryID,
                                 Title = g.Title,
                                 Description = g.Description,
                                 Price = g.Price,
                                 Location = g.Location,
                                 Created = g.Created,
                                 DistanceInMiles = (distance / 1609.344),
                             });
    items = items1;

This doesn't work because it loses all the relationships from the Include() statements in the first query.  I can't figure out how to do the same using something like this let keyword in the first service lambda query.  I'm trying not to query twice.  Is there a way to calculate a field in that first service query lambda so I could add the distance to each item?
I thought using projections might work but I couldn't get it to.

A:

items1 is a completely new set of Listing object, you are not "updating" values of the existing one. So because you don't copy over the ListingPictures and Category properties, they will be null. You need to do something like this in your projection:
select new Listing()
{
    ID = g.ID,                               
    CategoryID = g.CategoryID,
    Title = g.Title,
    Description = g.Description,
    Price = g.Price,
    Location = g.Location,
    Created = g.Created,
    DistanceInMiles = (distance / 1609.344),
    ListingPictures = g.ListingPictures, //Add this line
    Category = g.Category //and this line
});

Alternatively, it looks like you are just trying to update the DistanceInMiles property, that may be better done with a simple foreach loop.

