Entity Framework - Include Multiple Levels of Properties

前端 未结 8 850
囚心锁ツ
囚心锁ツ 2020-11-22 08:43

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

8条回答
  •  半阙折子戏
    2020-11-22 09:17

    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.

提交回复
热议问题