Home > Net >  EntityFramework Core - Retrieving List in objects
EntityFramework Core - Retrieving List in objects

Time:12-20

When I want to get a recipe from the database, the fields containing relationships to an another table are null. For exemple the ingredient object contains a foreign key to the Recipe table: RecipeId. So to avoid this:

[
    {
        "id": 1,
        "name": "Burger",
        "ingredients": [],
        "steps": [],
        "author": null
    }
]

I have to make all this:

    [HttpGet("{id}", Name = nameof(GetRecipeById))]
    public ActionResult GetRecipeById(int id)
    {
        Recipe recipe = _dataStore.GetRecipeById(id);
        
        return Ok(RetrieveRecipesInfos(recipe));
    }

    RecipeReadDTO RetrieveRecipesInfos(Recipe recipe) {
        if (recipe == null)
            return null;

        RecipeReadDTO recipeRead = _map.Map<RecipeReadDTO>(recipe);

        User u = _dataStore.GetUserInfos(recipe.UserLogin);
        if (u == null)
            return null;
        recipeRead.Author = _map.Map<UserReadDTO>(u);

        IEnumerable<Ingredient> ingredients = _dataStore.GetIngredientsByRecipeId(recipe.Id);
        recipeRead.Ingredients = _map.Map<List<IngredientReadDTO>>(ingredients);

        IEnumerable<Step> steps = _dataStore.GetStepsByRecipeId(recipe.Id);
        recipeRead.Steps = _map.Map<List<StepReadDTO>>(steps);
        
        return recipeRead;
    }
public Recipe GetRecipeById(int id)
        {
            return _context.Recipes.FirstOrDefault<Recipe>(r => r.Id == id);
        }

DbContext:

public class CookUsContext : DbContext
    {
        public CookUsContext(DbContextOptions<CookUsContext> options) : base(options)
        {
        }

        public DbSet<Recipe> Recipes { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Ingredient> Ingredients { get; set; }
        public DbSet<Step> Steps { get; set; }
    }
}

Is there an easiest and more efficient way of doing it? Because with multiple recipes to retrieve, it can easily become slow.

CodePudding user response:

you have lazy loading properly configured, but you need the Include() regardless as friends points out.

eager loading EF:

_context.Recipes.Include(rec => rec .Ingredient).FirstOrDefault(ob => ob .Id == id);

CodePudding user response:

try using include(), like _context.Recipes.Include(o => o.Ingredient).Include(o => o.Step).FirstOrDefault(o => .Id == id);

  • Related