我是C#和ASP.NET MVC的新手,我试图理解存储库模式。我读过很多文章,但我不明白如何使用它。我目前使用LINQ to SQL来访问我的SQL Server 2005数据库,为了测试目的,我创建了两个表。我有一个Employees
表和一个EmployeeContacts
表。两个表的pk都是用户名。存储库模式和MVC帮助
员工
- 用户名
- 名字
- 姓
- 位置
- 电子邮件
状态
雇佣日期
EmployeeContacts
- 用户名
- Contact1
- Contact1Phone
- Contact1Relationship
有一个一对一的相对两张桌子之间的关系。员工可以被添加,更新和删除,EmployeeContacts
表中的数据也可以被添加,更新和删除。
那么我会创建一个基本资源库供两个实体使用,还是应该为每个实体单独创建一个资源库?如果有人愿意告诉我一些很棒的代码。
到目前为止,我有这个Employee存储库。我也有一个EmployeeContacts
。
namespace MvcDirectoryLINQ.Models
{
public class EmployeeRepository
{
private TestDB_DataDataContext db = new TestDB_DataDataContext();
private UserName u = new UserName();
//
// Query Methods
public IQueryable<Employee> FindAllEmployees()
{
return db.Employees;
}
public IQueryable<Employee> FindRecentEmployees()
{
DateTime myDate = DateTime.Today.AddMonths(-6);
return from empl in db.Employees
where empl.HireDate >= myDate
orderby empl.HireDate
select empl;
}
public Employee GetEmployee(string UserName)
{
return db.Employees.SingleOrDefault(d => d.UserName == UserName);
}
//
// Insert/Delete Methods
public void Add(Employee employee)
{
// get the UserName which is created from the email
employee.UserName = u.ReturnUserName(employee.Email);
//Insert the new employee into the database
db.Employees.InsertOnSubmit(employee);
db.EmployeeContacts.InsertOnSubmit(employee.EmployeeContact);
}
public void Delete(Employee employee)
{
db.EmployeeContacts.DeleteOnSubmit(employee.EmployeeContact);
db.Employees.DeleteOnSubmit(employee);
}
//
// Persistence
public void Save()
{
db.SubmitChanges();
}
}
}
我有一个EmployeeFormViewModel
类:
namespace MvcDirectoryLINQ.Models
{
public class EmployeeFormViewModel
{
//Properties
public Employee Employee { get; private set; }
public EmployeeContact EmployeeContact { get; private set; }
//Constructor
public EmployeeFormViewModel(Employee employee, EmployeeContact employeeContact)
{
Employee = employee;
EmployeeContact = employeeContact;
}
}
}
代码EmployeeController
:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(string UserName, FormCollection formValues)
{
Employee employee = employeeRepository.GetEmployee(UserName);
EmployeeContact employeecontact = employeecontactRepository.GetContact(UserName);
try
{
UpdateModel(employee);
UpdateModel(employeecontact);
employeecontactRepository.Save();
employeeRepository.Save();
return RedirectToAction("Details", new { UserName = employee.UserName });
}
catch
{
foreach (var issue in employee.GetRuleViolations())
{
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
return View(new EmployeeFormViewModel(employee, attendingID));
}
}
在我看来,我从@model MvcDirectoryLINQ.Models.EmployeeFormViewModel
继承。我的员工数据保存正确,但EmployeeContacts不,我不知道为什么。
我是否正确实施存储库模式?
我发现了一个教程(http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs),显示我如何实现它实现像一个接口库模式你提到。我目前正在使用这个测试应用程序,所以我可以理解这个模式。这与Web Forms非常不同,我很难理解它。感谢您的帮助skaz和Konamiman。 – MikeB55
@ MikeB55 - 没问题。只是你知道,你也可以在Web表单上使用存储库模式。这是一个通用的概念。祝MVC好运。 – skaz