Пример #1
0
        public IHttpActionResult Register(AccountModel user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            List <user> existsLoginOrMail = _db.user.Where(x => x.login == user.Login || x.mail == user.Mail).ToList();

            if (existsLoginOrMail.Count > 0)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Login or Mail exists")));
            }

            using (DbContextTransaction dbtransaction = _db.Database.BeginTransaction())
            {
                try
                {
                    user newUser = new user()
                    {
                        login    = user.Login,
                        password = Auth.HashPassword(user.Password),
                        mail     = user.Mail
                    };
                    _db.user.Add(newUser);
                    _db.SaveChanges();

                    roles     roles        = _db.roles.Where(x => x.name == "user").First();
                    userRoles newUserRoles = new userRoles()
                    {
                        userId  = newUser.id,
                        rolesId = roles.id
                    };

                    _db.userRoles.Add(newUserRoles);
                    _db.SaveChanges();

                    newUser.rolesId = newUserRoles.id;

                    _db.user.Attach(newUser);
                    _db.Entry(newUser).State = EntityState.Modified;
                    _db.SaveChanges();

                    dbtransaction.Commit();
                }
                catch
                {
                    dbtransaction.Rollback();
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Register user failed!")));
                }

                return(Ok());
            }
        }
Пример #2
0
        public IHttpActionResult AddFood(FoodModel food)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            food newFood = new food()
            {
                userId = (int)food.UserId,
                foodName = food.FoodName,
                calories = (int)food.Calories,
                carbs = (int)food.Carbs,
                fat = (int)food.Fat,
                protein = (int)food.Protein
            };

            _db.food.Add(newFood);
            _db.SaveChanges();

            return Ok(newFood);
        }