The Include() method works quite well for Lists on objects. But what if I need to go two levels deep? For example, the method below will return ApplicationServers with the i
I made a little helper for Entity Framework 6 (.Net Core style), to include sub-entities in a nice way.
It is on NuGet now : Install-Package ThenInclude.EF6
using System.Data.Entity;
var thenInclude = context.One.Include(x => x.Twoes)
.ThenInclude(x=> x.Threes)
.ThenInclude(x=> x.Fours)
.ThenInclude(x=> x.Fives)
.ThenInclude(x => x.Sixes)
.Include(x=> x.Other)
.ToList();
The package is available on GitHub.
I'm going to add my solution to my particular problem. I had two collections at the same level I needed to include. The final solution looked like this.
var recipe = _bartendoContext.Recipes
.Include(r => r.Ingredients)
.ThenInclude(r => r.Ingredient)
.Include(r => r.Ingredients)
.ThenInclude(r => r.MeasurementQuantity)
.FirstOrDefault(r => r.Id == recipeId);
if (recipe?.Ingredients == null) return 0m;
var abv = recipe.Ingredients.Sum(ingredient => ingredient.Ingredient.AlcoholByVolume * ingredient.MeasurementQuantity.Quantity);
return abv;
This is calculating the percent alcohol by volume of a given drink recipe. As you can see I just included the ingredients collection twice then included the ingredient and quantity onto that.