大多数人会建议使用“存储库模式”将数据访问代码移出控制器(并使用模拟对象而不是真实数据库进行单元测试)。
这里有一些地方可以阅读更多内容:
编辑:
我强烈建议您阅读上面链接的整个 Scott Guthrie 章节。它有很多好的建议。也就是说,这里有一些相关的例子(本章除外)......
首先,我通常喜欢对“更新”和“添加”有不同的操作。即使它们是呈现表单的相同视图,使用不同的 URL 来发布编辑与发布新记录通常感觉更清晰。因此,控制器更新操作中使用的存储库模式如下所示:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues)
{
//get the current object from the database using the repository class
Dinner dinner = dinnerRepository.GetDinner(id);
try
{
//update the object with the values submitted
UpdateModel(dinner);
//save the changes
dinnerRepository.Save();
//redirect the user back to the read-only action for what they just edited
return RedirectToAction("Details", new { id = dinner.DinnerID });
}
catch
{
//exception occurred, probably from UpdateModel, so handle the validation errors
// (read the full chapter to learn what this extention method is)
ModelState.AddRuleViolations(dinner.GetRuleViolations());
//render a view that re-shows the form with the validation rules shown
return View(dinner);
}
}
这是“添加”示例:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create()
{
//create a new empty object
Dinner dinner = new Dinner();
try
{
//populate it with the values submitted
UpdateModel(dinner);
//add it to the database
dinnerRepository.Add(dinner);
//save the changes
dinnerRepository.Save();
//redirect the user back to the read-only action for what they just added
return RedirectToAction("Details", new { id = dinner.DinnerID });
}
catch
{
//exception occurred, probably from UpdateModel, so handle the validation errors
// (read the full chapter to learn what this extention method is)
ModelState.AddRuleViolations(dinner.GetRuleViolations());
//render a view that re-shows the form with the validation rules shown
return View(dinner);
}
}
对于上述两个示例,DinnerRepository 如下所示:
public class DinnerRepository
{
private NerdDinnerDataContext db = new NerdDinnerDataContext();
//
// Query Methods
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
public IQueryable<Dinner> FindUpcomingDinners()
{
return from dinner in db.Dinners
where dinner.EventDate > DateTime.Now
orderby dinner.EventDate
select dinner;
}
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}
//
// Insert/Delete Methods
public void Add(Dinner dinner)
{
db.Dinners.InsertOnSubmit(dinner);
}
public void Delete(Dinner dinner)
{
db.RSVPs.DeleteAllOnSubmit(dinner.RSVPs);
db.Dinners.DeleteOnSubmit(dinner);
}
//
// Persistence
public void Save()
{
db.SubmitChanges();
}
}