Beispiel #1
0
        public async Task <IActionResult> CreateMeal(long userId, [FromBody] MealDto mealDto)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            long?mealId = null;

            using (var tx = TransactionScopeBuilder.New())
            {
                var user = dbContext
                           .Set <User>()
                           .First(u => u.Id == userId);

                // NOTE: with DDD it would be a user.AddMeal(date, calories, desc) where inside I'd set the back-ref to User as well (always valid object graph)!
                var meal = new UserMeal()
                {
                    Date        = mealDto.Date,
                    Calories    = mealDto.Calories,
                    Description = mealDto.Description
                };

                user.Meals.Add(meal);

                // it's not NH, so to get the ID we need to save
                await dbContext.SaveChangesAsync();

                mealId = meal.Id;

                tx.Complete();
            }

            return(this.Created(mealId));
        }
Beispiel #2
0
        public async Task <IActionResult> UpdateMeal(long userId, long mealId, [FromBody] MealDto mealDto)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            using (var tx = TransactionScopeBuilder.New())
            {
                var meal = (
                    from u in dbContext.Set <User>()
                    from m in u.Meals
                    where u.Id == userId && m.Id == mealId
                    select m
                    ).First();

                meal.Date        = mealDto.Date;
                meal.Calories    = mealDto.Calories;
                meal.Description = mealDto.Description;

                await dbContext.SaveChangesAsync();

                tx.Complete();
            }

            return(Ok());
        }