0

I have this code to get all Meal from the database but considering optimization, i want to only get the entities needed, instead of returning all.

public async Task<IEnumerable<Meal>> GetAllMeal()
        {
            return await _dbSet.Include(x => x.MealPrices).ToListAsync();
        }

The above code will fetch all entities from the database including the ones i don't need. Is there a way to map my dto at the point of fetching the data from db

  • Your database tables are already classes, that is how you access them. if you want to do another level of mapping you can either use AutoMapper, or if you want to pull a few columns, you can use the `EF Select` eg. `_dbSet.Include(x => x.MealPrices).Select(m => new{ object1 =m.Id, object2 = m.AnotherColumn}).ToListAsync();`, you can also map to an exiting object as `_dbSet.Include(x => x.MealPrices).Select(m => new ExitingObject{ Id =m.Id, Column1 = m.AnotherColumn}).ToListAsync();` This https://stackoverflow.com/questions/19536064/select-multiple-columns-using-entity-framework can also help – Bosco Dec 02 '21 at 00:28

1 Answers1

0

I think you're looking for the Where clause. For example, if your Meal model has an integer Id as the primary key you could do this:

    public async Task<Meal> GetMealById(int id)
        {
            return await _dbSet
              .Include(x => x.MealPrices)
              .Where(y => y.Id == id)
              .FirstOrDefault();
        }
DCAggie
  • 144
  • 8