EntityFramework-.Select()带有匿名对象的投影引发了一个我不确定如何解释的异常

时间:2019-03-01 10:23:50

标签: c# entity-framework entity-framework-6

例外

  

包含路径表达式必须引用在类型上定义的导航属性。使用虚线路径作为参考导航属性,使用“选择”运算符作为集合导航属性。

这是导致此情况的电话。 VignetteCollection,因此我认为该陈述应有效。

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;
    }
}

我在这里想念什么?

1 个答案:

答案 0 :(得分:1)

您不能包含匿名类型的选择:

.Include(e => e.SharedCar.Vignette
    .Select(v => new
    {
        v.Id,
        v.GUID,
        v.CountryName,
        v.CountryCode
    })
)

相反,直接包含相关对象:

.Include(e => e.SharedCar.Select(s => s.Vignette))

如果您只想从Vignette中获取某些值,则可以通过添加.Select(x => new CarSharingEntry { ... })并在ToList()之前指定要对每个项目进行的操作来做到这一点< / p>

.Select(e => new CarSharingEntry {
    ShareMeeting = e.ShareMeeting,
    SelectedOptions = e.SelectedOptions,
    SharedCar = new SharedCar {
        Vignette = e.SharedCar.Vignette.Select(v => new {
            v.Id,
            v.GUID,
            v.CountryName,
            v.CountryCode
        }),
        VehicleType = e.SharedCar.VehicleType,
        Equipment = e.SharedCar.Equipment,
        // etc, etc...
    },        
}).ToList()