0

I have the following database entity containing ingredients to put on pizza. Column Type is a foreign key to another table containing information on the ingredient category (cheese, meat, vegetables etc.)

public class Ingredient
{
    public int IngredientId { get; set; }

    public string Name { get; set; }

    public bool IsVegetarian { get; set; }

    public int Type { get; set; }
}

Some sample data: sample ingredients

For each unique 'Type' value, I want to return a List of Ingredients with that type. The final result will be stored in an ICollection of type IngredientViewModel.

public class IngredientViewModel : Model
{
    public IngredientCategory Category { get; set; }

    public List<Ingredient> Ingredients { get; set; }
}

How can I best get all ingredients, grouped per category in a single database trip using linq or lambda expressions?

I currently have the following snippet which I find a bit messy:

public async Task<IEnumerable<IngredientViewModel>> GetIngredientsPerCategoryAsync()
{
        IEnumerable<Ingredient> result = await _repo.GetAllAsync();

        IEnumerable<IngredientViewModel> viewModels = result.GroupBy(
            x => x.Type,
            (category, ingredients) => new IngredientViewModel()
            {
                Category = (IngredientCategory)category,
                Ingredients = MapFromEntities(ingredients)
            })
            .OrderBy(x => x.Category.ToString())
            .ToList();

        return viewModels;
}

1 Answers1

0

The most obvious would be: Ingredients = g.ToList().

Marty
  • 412
  • 3
  • 7