EntityFramework - .Select() Projection with anonymous object throws a Exception that I am not sure how to interpret

c# entity-framework entity-framework-6

Question

Exception

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.

This is the call causing this. Vignette is a Collection, so in my opinion this statement should be valid.

public ICollection<CarSharingEntry> GetAllCarSharingEntriesByUserSAM(string userSAM)
{
    try
    {
        using (var _dbContext = new CarSharingContext())
        {
            _dbContext.Configuration.LazyLoadingEnabled = false;
            return _dbContext.CarSharingEntries
                .Include(e => e.ShareMeeting)
                .Include(e => e.SelectedOptions)
                .Include(e => e.SharedCar)

                 // Code Block causing this v
                .Include(e => e.SharedCar.Vignette
                    .Select(v => new
                    {
                        v.Id,
                        v.GUID,
                        v.CountryName,
                        v.CountryCode
                    })
                )
                // ---------------------------
                .Include(e => e.SharedCar.VehicleType)
                .Include(e => e.SharedCar.Equipment)
                .Include(e => e.SharedCar.FuelType)
                .Include(e => e.SharedCar.Location)
                .Include(e => e.CarSharer.Select(c => c.ContactDetails))
                .Where(e => e.SharedCar.isForCarSharing)
                // Commented out for debugging
                //.Where(e => e.CarSharer.Any(p => p.SAM == userSAM))
                .ToList();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

What am I missing here?

1
0
3/2/2019 3:09:05 PM

Accepted Answer

You cannot use Include to select data like this. Include is used to load related data. You should load your entities using Include then select what you want. Remember to remove .ToString() from CompanyId. EF will do it for you. Your query should look like this:

var incomeList = ctx.IncomeLists
    .Include(i => i.Company)
    .Include(i => i.ListPeriods.Select(lp => lp.PeriodType))
    .Select(i => new 
    {
        CompanyTitle =  i.CompanyId + "/" + i.Company.CompanyName,
        PeriodTypeNames = i.ListPeriods.Select(lp => lp.PeriodType.PeriodTypeName)
    })
    .ToList();
23
9/28/2017 5:04:38 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow