Entity Framework with Include and Select together
may be:
var program = (from p in mEntities.Programs
where p.Id ==Id
select new {
Program = p,
ProgramFoodTypes = from pf in p.ProgramFoodTypes
where pf.IsActive
select pf,
ProgramFoods = p.ProgramFoods.Select(y => new {
Food = y.Food,
Type = y.FoodType
})
}).ToArray().Select(m => m.Program);
For your second solution, I think you can use:
var program = (from p in mEntities.Programs
.Include(p => p.ProgramFoods.Select(f => f.Food))
.Include(p => p.ProgramFoods.Select(f => f.FoodType))
where p.Id == Id
select new {
Program = p,
ProgramFoodTypes = from pf in p.ProgramFoodTypes
where pf.IsActive
select pf,
p.ProgramFoods
}).ToArray().Select(m => m.Program);
update:
Since you're using anonymous type in your linq query, Include statements are dismissed.
You'd have to load all related ProgramFoodTypes
on client side, and then do the filtering:
var program = mEntities.Programs
.Include(p => p.ProgramFoodTypes)
.Include(p => p.ProgramFoods.Select(f => f.Food))
.Include(p => p.ProgramFoods.Select(f => f.FoodType))
.SingleOrDefault(m => m.Id == Id);
program.ProgramFoodTypes = program.ProgramFoodTypes.Where(pft => pft.IsActive);
You can use AsNoTracking()
or clone the returned Program
object in a new object in case you want to make sure your data will be intact on db-side.