Entity Framework - Include Multiple Levels of Properties

前端 未结 8 703
囚心锁ツ
囚心锁ツ 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:16

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题