SaveChanges() public méthode

public SaveChanges ( bool acceptAllChangesOnSuccess ) : int
acceptAllChangesOnSuccess bool
Résultat int
        // PUT api/Users/5
        public HttpResponseMessage PutUser(int id, User user)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (id != user.Id)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            db.Entry(user).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Exemple #2
0
        public ActionResult Create(Thread t, FormCollection form)
        {
            ForumContext context = new ForumContext();
            Thread       thread  = new Thread();

            thread.startpost = t.startpost;
            thread.BoardId   = t.BoardId;
            thread.title     = t.title;
            thread.status    = "Unlocked";
            context.thread.Add(thread);
            context.SaveChanges();
            Post post = new Post();

            post.postType    = "start";
            post.ThreadID    = thread.id;
            post.description = thread.startpost;
            post.postedAt    = DateTime.Now;
            post.postType    = "Thread_Reply";
            //FormCollection form = new FormCollection();
            post.postedBy = Convert.ToInt32(form["startedBy"]);
            context.post.Add(post);

            context.SaveChanges();
            return(RedirectToAction("Details", "Forum", new { id = t.BoardId }));
        }
Exemple #3
0
 public ActionResult ChangePassword(ChangePasswordModel model)
 {
     if (ModelState.IsValid)
     {
         User user = db.Users.FirstOrDefault(p => p.Id == model.UserId);
         if (user != null)
         {
             // Если введенный старый пароль совпадает с паролем в БД
             if (user.Password == LoginHelper.GetHash(model.PasswordOld))
             {
                 // Изменяем пароль
                 user.Password        = LoginHelper.GetHash(model.Password);
                 db.Entry(user).State = EntityState.Modified;
                 db.SaveChanges();
                 return(RedirectToAction("Profile/" + user.Login, "Account"));
             }
             // иначе добавляем сообщение об ошибке
             else
             {
                 ModelState.AddModelError("", "Неверный старый пароль!");
             }
         }
         else
         {
             ModelState.AddModelError("", "Ошибка при изменении пароля...");
         }
     }
     return(View(model));
 }
Exemple #4
0
        public int CreateForum(Forum forum)
        {
            var new_forum = context.forums.Add(forum);

            context.SaveChanges();
            return(new_forum.Entity.id);
        }
 public ActionResult Create(MessageEdit model)
 {
     if (ModelState.IsValid)
     {
         // Получаем записи темы и пользователя из БД
         Topic topic = db.Topics.FirstOrDefault(p => p.Id == model.TopicId);
         User  user  = db.Users.FirstOrDefault(p => p.Login == User.Identity.Name);
         // Если такие записи есть
         if (topic != null && user != null)
         {
             // сохраняем сообщение в БД
             Message msg = new Message();
             msg.Content  = model.Content;
             msg.Dates    = DateTime.Now;
             msg.Disabled = false;
             msg.Topic    = topic;
             msg.User     = user;
             db.Messages.Add(msg);
             db.SaveChanges();
             // редирект к списку сообщений
             return(RedirectToAction("List/" + model.TopicId));
         }
         else
         {
             ModelState.AddModelError("", "Ошибка при сохранении");
         }
     }
     return(View(model));
 }
Exemple #6
0
        public async Task <IActionResult> CreateComment(string content, int postId)
        {
            // If vm state is valid:
            if (ModelState.IsValid)
            {
                // Gets the currently logged in user
                var currentUser = await _userManager.FindByNameAsync(User.Identity.Name);

                // Creates a new comment with the given parameters
                var comment = new Comment()
                {
                    AuthorName = currentUser.UserName,
                    Content    = content,
                    DatePosted = DateTime.Now,
                    Post       = _db.Posts.Find(postId)
                };

                // Add the comment to the database and post
                _db.Comments.Add(comment);
                _db.Posts.Find(postId).Comments.Add(comment);
                _db.SaveChanges();

                // Return to the original post that was commented on
                return(RedirectToAction("ViewPost", "Post", new { postId }));
            }
            // If invalid, return to the post
            return(RedirectToAction("ViewPost", "Post", new { postId }));
        }
        public void Delete(int postId)
        {
            var post = _forumContext.Posts.Find(postId);

            _forumContext.Posts.Remove(post);
            _forumContext.SaveChanges();
        }
        public IHttpActionResult AddOneStory([FromBody] ViewModels.CreateStoryViewModel createStory)
        {
            var category = db.Categories.SingleOrDefault(s => s.CategoryName == createStory.Category);

            if (category == null)
            {
                return(BadRequest());
            }

            Author author = null;

            if (!string.IsNullOrWhiteSpace(createStory.Author))
            {
                author = db.Authors.SingleOrDefault(s => s.AuthorName == createStory.Author);
                if (author == null)
                {
                    author = db.Authors.Add(new Author {
                        AuthorName = createStory.Author
                    });
                    db.SaveChanges();
                }
            }
            var story = db.Stories.Add(new Story
            {
                Author   = author,
                Category = category,
                Headline = createStory.Headline,
                Body     = createStory.Body
            });

            db.SaveChanges();
            return(Ok(story.ID));
        }
 public IActionResult Register(RegisterModel model)
 {
     if (ModelState.IsValid)
     {
         User user = db.Users.FirstOrDefault(u => u.Login == model.Login);
         if (user == null)
         {
             user = new User {
                 Login = model.Login, Password = model.Password, Email = model.Email, About = model.About
             };
             Role userRole = db.Roles.FirstOrDefault(r => r.Name == "user");
             if (userRole != null)
             {
                 user.Role = userRole;
             }
             db.Users.Add(user);
             db.SaveChanges();
             Authenticate(user);
             return(RedirectToAction("Index", "Home"));
         }
         else
         {
             ModelState.AddModelError("", "Пользователь с данным именем уже существует");
         }
     }
     return(View(model));
 }
        public TEntity Add(TEntity entity)
        {
            var result = _context.Set <TEntity>().Add(entity).Entity;

            _context.SaveChanges();

            return(result);
        }
Exemple #11
0
 public ActionResult Edit([Bind(Include = "DiscussionId,Posted,Title,Text,PosterId")] Discussion discussion)
 {
     if (ModelState.IsValid)
     {
         db.Entry(discussion).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index", "Discussion"));
     }
     return(View(discussion));
 }
Exemple #12
0
        public ActionResult CreateTopic(Topic topic, string IsMessagingStr)
        {
            topic.IsMessaging = IsMessagingStr == "true" ? true : false;
            topic.Date        = DateTime.Now;
            db.Topics.Add(topic);
            db.SaveChanges();
            var topicMy = db.Topics.ToList().FirstOrDefault(n => n.Date == topic.Date);

            return(RedirectToAction("Topic", "Home", new { id = topicMy.Id }));
        }
 public void Post([FromBody] TopicViewModel model)
 {
     context.Topics.Add(new Topic()
     {
         Content    = model.Content,
         CreateTime = DateTime.Now,
         Title      = model.Title
     });
     context.SaveChanges();
 }
Exemple #14
0
 public ActionResult Edit([Bind(Include = "id,username,pass,AboutMe,JoinedDate")] User user)
 {
     if (ModelState.IsValid)
     {
         db.Entry(user).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index", "Discussion"));
     }
     return(View(user));
 }
Exemple #15
0
 public IActionResult CreateCategory(Categories newCategory)
 {
     if (ModelState.IsValid)
     {
         if (!_context.categories.Any(c => c.Name == newCategory.Name))
         {
             Categories new_category = new Categories
             {
                 Name = newCategory.Name,
             };
             _context.Add(new_category);
             _context.SaveChanges();
             return(RedirectToAction("Index"));
         }
         ModelState.AddModelError("Name", "This category already exists.");
     }
     ViewBag.UserName   = _userManager.GetUserName(HttpContext.User);
     ViewBag.Categories = _context.categories.Include(c => c.Moderators).ThenInclude(m => m.User).Include(c => c.Topics);
     ViewBag.Role       = false;
     if (HttpContext.User.IsInRole("Level2"))
     {
         ViewBag.Role = true;
     }
     return(View("Index"));
 }
Exemple #16
0
 public IEnumerable <string> Get()
 {
     this.context.Topics.Add(new Topic()
     {
         Content    = "test",
         CreateTime = DateTime.Now,
         Title      = "hello"
     });
     context.SaveChanges(true);
     return(new string[] { "value1", "value2" });
 }
Exemple #17
0
        public IActionResult Post([FromBody] User user)
        {
            if (user == null)
            {
                return(BadRequest());
            }

            db.Users.Add(user);
            db.SaveChanges();
            return(Ok(user));
        }
Exemple #18
0
 public IActionResult Create(Post newPost)
 {
     if (ModelState.IsValid == false)
     {
         return(View("New"));
     }
     newPost.UserId = (int)uid;
     db.Posts.Add(newPost);
     db.SaveChanges();
     return(RedirectToAction("All", newPost));
 }
Exemple #19
0
        public ActionResult Create([Bind(Include = "ID,ForumThreadID,Title,Text,PublishDate,Author")] ForumPost forumPost)
        {
            if (ModelState.IsValid)
            {
                db.ForumPosts.Add(forumPost);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(forumPost));
        }
 public void CreateUniversity(string countryId, string name, string website)
 {
     _context.Universities.Add(
         new University
     {
         CountryId = countryId,
         Name      = name,
         Website   = website
     });
     _context.SaveChanges();
 }
        public ActionResult Create([Bind(Include = "IdKategorii,NazwaKategorii,OpisKategorii,IdIkony")] Kategoria kategoria)
        {
            if (ModelState.IsValid)
            {
                db.Kategorie.Add(kategoria);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.IdIkony = new SelectList(db.Ikony, "IdIkony", "NazwaIkony", kategoria.IdIkony);
            return(View(kategoria));
        }
Exemple #22
0
 public ActionResult Edit([Bind(Include = "id,Text,Posted,DiscussionId,PosterId")] Post post)
 {
     if (ModelState.IsValid)
     {
         db.Entry(post).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index", "Discussion"));
     }
     ViewBag.DiscussionId = new SelectList(db.discussionDB, "DiscussionId", "Title", post.DiscussionId);
     ViewBag.PosterId     = new SelectList(db.userDB, "id", "username", post.PosterId);
     return(View(post));
 }
Exemple #23
0
 // Remove Post
 public void Delete(int postID)
 {
     try
     {
         context.Posts.Remove(GetPostById(postID));
     }
     catch (Exception)
     {
         throw new NotImplementedException();
     }
     context.SaveChanges();
 }
        public ActionResult Create([Bind(Include = "ID,Title,Description,addedBy")] ForumSection forumSection)
        {
            if (ModelState.IsValid)
            {
                forumSection.addedBy = User.Identity.Name;
                db.ForumSections.Add(forumSection);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(forumSection));
        }
Exemple #25
0
 public IActionResult Create(Post newPost)
 {
     if (ModelState.IsValid)
     {
         _db.Posts.Add(newPost);
         _db.SaveChanges();
         return(RedirectToAction("All"));
     }
     else
     {
         return(View("New"));
     }
 }
        public IActionResult Create()
        {
            Topic topic = new Topic
            {
                CreationDate = DateTime.Now,
                Creator      = db.Users.FirstOrDefault(u => u.Login == User.Identity.Name),
            };

            db.Topics.Add(topic);
            db.SaveChanges();
            return(RedirectToAction("TopicEdit", new RouteValueDictionary(
                                        new { controller = "DataBases", action = "TopicEdit", Id = topic.Id })));
        }
Exemple #27
0
        public IActionResult AddMember(int idEvent, EventMember member)
        {
            if (_context.Events.Find(idEvent) == null)
            {
                return(NotFound());
            }

            member.EventID = idEvent;

            _context.EventMembers.Add(member);
            _context.SaveChanges();
            return(Ok());
        }
Exemple #28
0
        public void AddUser(User user)
        {
            foreach (var users in context.usersData.ToList())
            {
                if (users.UserLogin == user.UserLogin)
                {
                    throw new Exception();
                }
            }
            context.usersData.Add(user);

            context.SaveChanges();
        }
        public HttpResponseMessage PostRegisterUser(UserModel model)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
            {
                var context = new ForumContext();
                using (context)
                {
                    this.ValidateUsername(model.Username);
                    this.ValidateNickname(model.Nickname);
                    this.ValidateAuthCode(model.AuthCode);
                    var usernameToLower = model.Username.ToLower();
                    var nicknameToLower = model.Nickname.ToLower();
                    var user            = context.Users.FirstOrDefault(
                        usr => usr.Username == usernameToLower ||
                        usr.Nickname.ToLower() == nicknameToLower);

                    if (user != null)
                    {
                        throw new InvalidOperationException("Users exists");
                    }

                    user = new User()
                    {
                        Username = usernameToLower,
                        Nickname = model.Nickname,
                        AuthCode = model.AuthCode
                    };

                    context.Users.Add(user);
                    context.SaveChanges();

                    user.SessionKey = this.GenerateSessionKey(user.Id);
                    context.SaveChanges();

                    var loggedModel = new LoggedUserModel()
                    {
                        Nickname   = user.Nickname,
                        SessionKey = user.SessionKey
                    };

                    var response =
                        this.Request.CreateResponse(HttpStatusCode.Created,
                                                    loggedModel);
                    return(response);
                }
            });

            return(responseMsg);
        }
Exemple #30
0
        public IActionResult BanUser(int id)
        {
            var user = _context.Users.Find(id);

            if (user == null)
            {
                return(NotFound());
            }

            user.Ban = true;
            _context.Users.Update(user);
            _context.SaveChanges();
            return(Ok());
        }
        static void Main()
        {
            var context = new ForumContext();

            /*-----------------------------------------------*/
            //var user = new User
            //{
            //    FirstName = "Pesho",
            //    LastName = "Goshev",
            //    Gender = Gender.NotSpedified,
            //    Username = "******",
            //    RegisteredOn = DateTime.Now
            //};

            //context.Users.Add(user);

            /*-----------------------------------------------*/

            //var question = new Question
            //{
            //    Content = "Alcohol",
            //    Title = "daite pls",
            //    AuthorId = 1
            //};

            //context.Questions.Add(question);

            /*-----------------------------------------------*/

            //var question = context.Questions.Find(2);
            //question.Tags.Add(new Tag()
            //    {
            //        Name = "Drugi prikazki"
            //    });

            //question.Tags.Add(new Tag()
            //{
            //    Name = "Vajni saobshteniya"
            //});

            //context.SaveChanges();

            //foreach (var tag in question.Tags)
            //{
            //    Console.WriteLine(tag.Name);
            //}

            /*-----------------------------------------------*/

            //var user = context.Users.Find(1);

            var users = context.Users.ToList();

            foreach (var friend in users[0].Friends)
            {
                Console.WriteLine(friend.FirstName + " " + friend.LastName);
            }

            context.SaveChanges();
        }