コード例 #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 UpdateFood([FromUri] int? id, [FromBody] FoodModel food)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            List<food> foods = _db.food.Where(x => x.id == id).ToList();

            if (foods.Count != 1)
                return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Food not found"));

            food foodFromDb = FoodModel.Update(foods.First(), food);

            _db.food.Attach(foodFromDb);
            _db.Entry(foodFromDb).State = EntityState.Modified;
            int result = _db.SaveChanges();

            if (result == 1)
                return Ok();


            return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ""));
        }