我想知道我在这里是否是好的做法。将实体框架代码优先与 MVC 和视图模型一起使用。下面我有用于列表、创建、编辑和删除的代码。模型名称 Page 和 2 个 ViewModel 名称为 ContentViewModel 和 ContentListViewModel。
private readonly IUserService _userService;
//private readonly MembershipProvider _members;
public ContentController()
{
// _members = Membership.Provider;
_userService = new AspNetMembershipProviderWrapper();
}
//
// GET: /Profile/Content/
public ActionResult Index()
{
using (var db = new BlogContext())
{
IEnumerable<Page> pages;
pages = db.ArticlePages.ToList();
List<ContentListViewModel> model = new List<ContentListViewModel>();
foreach (Page pg in pages)
{
MembershipUser user = _userService.Get(pg.authorId);
model.Add(new ContentListViewModel()
{
PageID = pg.pageID,
UserName = user.UserName,
UserID = (Guid)user.ProviderUserKey,
IsFrontPage = pg.frontpage,
isPublished = pg.published,
PageTitle = pg.titleHeading,
PageUrlName = pg.idName,
PublishedDate = pg.datentime
});
}
return View(model);
}
}
//
// GET: /Profile/Content/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Profile/Content/Create
[HttpPost]
public ActionResult Create(ContentViewModel page)
{
if (ModelState.IsValid)
{
using (var db = new BlogContext())
{
db.ArticlePages.Add(new Page()
{
authorId = (Guid)Membership.GetUser().ProviderUserKey,
datentime = DateTime.Now,
frontpage = page.FrontPage,
published = page.Published,
titleHeading = page.TitleHeading,
pageContent = page.Content,
idName = page.IdName
});
db.SaveChanges();
return RedirectToAction("Index").Success("Page added Successfully.");
}
}
return View(page);
}
//
// GET: /Profile/Content/Edit/5
public ActionResult Edit(int id = 0)
{
if (id == 0)
{
return RedirectToAction("Index").Error("Page Not found.");
}
Page pg = new Page();
using (var db = new BlogContext())
{
pg = (from m in db.ArticlePages where m.pageID == id select m).SingleOrDefault();
}
if (pg == null)
{
return RedirectToAction("Index").Error("Page Not found..");
}
return View(new ContentViewModel()
{
id = pg.pageID,
Content = pg.pageContent,
FrontPage = pg.frontpage,
Published = pg.published,
TitleHeading = pg.titleHeading,
IdName = pg.idName
});
}
// POST: /Profile/Content/Edit/5
[HttpPost]
public ActionResult Edit(ContentViewModel page)
{
if (ModelState.IsValid)
{
using (var db = new BlogContext())
{
var oPage = db.ArticlePages.Single(p => p.pageID == page.id);
oPage.frontpage = page.FrontPage;
oPage.idName = page.IdName;
oPage.pageContent = page.Content;
oPage.published = page.Published;
oPage.titleHeading = page.TitleHeading;
db.SaveChanges();
return RedirectToAction("Index").Success("Page updated");
}
}
return View(page);
}
//
// POST: /Profile/Content/Delete/5
[HttpPost]
public ActionResult Delete(int id)
{
using (var db = new BlogContext())
{
Page page = db.ArticlePages.Find(id);
db.ArticlePages.Remove(page);
db.SaveChanges();
return RedirectToAction("Index").Success("Page deleted");
}
}
我想知道有没有更好的方法来做到这一点?