Save data instead of adding to database
我正在尝试在asp.net mvc项目中编辑一篇文章。这是创建项目时的工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public ActionResult Create(ArticleViewModel model) { if (ModelState.IsValid) { try { // Get the userID who created the article User usr = userrepo.FindByUsername(User.Identity.Name); model.UsernameID = usr.user_id; repository.AddArticle(model.Title, model.Description, model.ArticleBody); } catch (ArgumentException ae) { ModelState.AddModelError("", ae.Message); } return RedirectToAction("Index"); } return View(model); } |
在我的存储库中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | public void AddArticle(string Title, string Description, string ArticleBody) { item Item = new item() { item_title = Title, item_description = Description, article_body = ArticleBody, item_createddate = DateTime.Now, item_approved = false, user_id = 1, district_id = 2, link ="", type = GetType("Article") }; try { AddItem(Item); } catch (ArgumentException ae) { throw ae; } catch (Exception) { throw new ArgumentException("The authentication provider returned an error. Please verify your entry and try again." + "If the problem persists, please contact your system administrator."); } Save(); // Immediately persist the User data } public void AddItem(item item) { entities.items.Add(item); } |
但是现在我要编辑一篇文章,这是我到目前为止所拥有的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public ActionResult Edit(int id) { var model = repository.GetArticleDetails(id); return View(model.ToList()); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(ArticleViewModel model) { if (ModelState.IsValid) { // Attempt to register the User try { item Item = repository.GetArticleDetailsByTitle(model.Title); Item.item_title = model.Title; Item.item_description = model.Description; Item.article_body = model.ArticleBody. // HERE I NEED TO SAVE THE NEW DATA return RedirectToAction("Index","Home"); } catch (ArgumentException ae) { ModelState.AddModelError("", ae.Message); } } // If we got this far, something failed, redisplay form return View(model); } |
如您所见,我检查了调整后的文本并将其放在"项目"中。但是如何将其保存在数据库中? (我的存储库中的函数)
我认为您的
因此您想在此处调用该
1 2 3 4 5 6 7 8 9 10 | try { item Item = repository.GetArticleDetailsByTitle(model.Title); Item.item_title = model.Title; Item.item_description = model.Description; Item.article_body = model.ArticleBody. **Save();** return RedirectToAction("Index","Home"); } |
-
应该只需要
save ()方法,就不需要AddItem ()方法。
恐怕您需要再次从数据库中获取文章,对其进行更新并保存更改。实体框架会自动跟踪实体的更改,因此您的存储库中应为:
1 2 3 4 5 6 7 8 9 |