前段时间我和 OP 处于一个非常相似的地方,所以我将在了解存储库模式后用一些代码来扩展 Roberts 的答案,说明我如何构建我的 asp.net mvc 应用程序。
所以你的项目是 QandA
您将拥有一个名为QandA.data 的类库项目,您将在这里创建您的 edmx 文件和所有实体框架类。然后你有一个像这样的每个实体的存储库:
public interface IRepository<T>
{
T Save(T entity);
void Delete(T entity);
IQueryable<T> GetAll();
T GetById(int id);
}
然后您可以拥有一个工厂或使用依赖注入来获取实际的存储库。所以:
class QuestionRepo : IRepository<Question>
{
//call xxxEntites and get/save/delete yourentities here.
}
static class RepositoryFactory
{
public static IRepository<Question> GetQuestionRepo()
{
return new QuestionRepo();
}
}
然后在你的调用代码中(在你的 asp.net 项目中)你有
IRepository<Question> qRepo = RepositoryFactory.GetQuestionRepo();
Question q = qRepo.GetById(1);
现在执行上述操作的好处是,您的调用代码不知道实体是如何通过的,因此您可以创建一个模拟存储库来测试您的应用。
static class RepositoryFactory
{
public static IRepository<Question> GetQuestionRepo()
{
return new FakeQuestionRepo();
//create your own fake repo with some fixed fake data.
}
}
现在,如果您将代码扔到假的或真实的存储库中,您调用的代码根本不会改变。
此外,罗伯特在他的问题中谈到的是 ViewModel。因此,您不会制作 Question 类型的强类型页面。所以你有
class QuestionForm
{
public string Title
public string QuestionContent
}
您的页面将是 QuestionForm 类型,但在您的创建控制器中,您将从问题表单中获取数据,将其填写到您的问题实体中,然后通过存储库发送。
[HttpPost]
public ActionResult Create(QuestionForm quesfrm)
{
IRepository<Question> qRepo = RepositoryFactory.GetQuestionRepo();
Question ques = new Question {
AskedDate = DateTime.Now,
Title = quesfrm.Title,
Content = QuestionContent
}
qRepo.Save(ques);
}
Robert 提到了您这样做的原因之一,还有其他一些原因,您可以阅读更多关于 SO 上的视图模型的信息。另请查看nerddinner 的代码
您可能希望看到这些 SO 问题:
Should repositories implement IQueryable<T>?
Repository pattern: One repository class for each entity?
希望对你有所帮助。