public async Task AddMealToDiaryAsync(int mealId, string userId, double quantity) { var user = this.userRepository .All() .Where(x => x.Id == userId) .FirstOrDefault(); var meal = this.mealRepository .AllAsNoTracking() .Where(x => x.Id == mealId) .FirstOrDefault(); user.RemainingCalories -= meal.KCal * quantity; user.RemainingProtein -= meal.Protein * quantity; user.RemainingCarbs -= meal.Carbs * quantity; user.RemainingFat -= meal.Fat * quantity; var mealDiary = new MealDiary { MealId = mealId, UserId = userId, MealQuantity = quantity, }; await this.mealsDiaryRepository.AddAsync(mealDiary); await this.mealsDiaryRepository.SaveChangesAsync(); await this.userRepository.SaveChangesAsync(); }
public async Task TesDeleteMealFromDiaryAsyncShouldReturnCorectly() { ApplicationDbContext db = GetDb(); var mealsDiaryRepository = new EfDeletableEntityRepository <MealDiary>(db); var userRepository = new EfDeletableEntityRepository <ApplicationUser>(db); var mealRepository = new EfDeletableEntityRepository <Meal>(db); var workoutExerciseRepository = new EfRepository <WorkoutExercise>(db); var service = new DiariesService( mealsDiaryRepository, userRepository, mealRepository, workoutExerciseRepository); var user = new ApplicationUser { Id = "userId", RemainingCalories = 800, RemainingProtein = 800, RemainingCarbs = 800, RemainingFat = 800, DailyCalories = 1800, Protein = 1800, Carbs = 1800, Fat = 1800, }; var meal = new Meal { Id = 1, KCal = 100, Protein = 100, Carbs = 100, Fat = 100, }; var mealDiary = new MealDiary { MealId = 1, UserId = "userId", MealQuantity = 2, }; var mealDiaryTwo = new MealDiary { MealId = 2, UserId = "userId", }; await db.Users.AddAsync(user); await db.Meals.AddAsync(meal); await db.MealsDiary.AddAsync(mealDiary); await db.MealsDiary.AddAsync(mealDiaryTwo); await db.SaveChangesAsync(); await service.DeleteMealFromDiaryAsync(1, "userId"); Assert.Single(db.MealsDiary.Where(x => x.UserId == "userId" && x.MealId == 2)); Assert.Equal(1000, user.RemainingCalories); Assert.Equal(1000, user.RemainingProtein); Assert.Equal(1000, user.RemainingCarbs); Assert.Equal(1000, user.RemainingFat); }