I have been looking around for an answer to my question but couldn't find one, mostly because I don't really know how to phrase it!
I am playing around with EF code first and trying to implement some sort of repository pattern whilst using dependency injection (thanks to Unity). I am also trying to keep to SOLID (well, the SRP part at least) in that I have IStaffRepository
and IDepartmentRepository
interfaces which in turn implement IRepository<TEntity>
which provides basic CRUD
methods.
My question is, how can I keep to the SRP when I need to update a staff members' department?
I have read that it is bad practice to use a single DbContext
instance for all repositories due to possible memory leaks and so I cannot simply call the IDepartmentRepository
to get the new department as this would use a separate instance of my DbContext
.
The obvious solution to me is to include something like...
Department GetDepartment(int id);
Within IStaffRepository
- but would this not break the SRP?
The code I have in my Controller is...
private IStaffRepository repository;
private IDepartmentRepository departmentRepository;
public StaffController(IStaffRepository repository, IDepartmentRepository departmentRepository)
{
this.repository = repository;
this.departmentRepository = departmentRepository;
}
public ActionResult Edit(int id)
{
return View(new StaffViewModel(repository.GetItem(id)));
}
[HttpPost]
public ActionResult Edit(int id, StaffViewModel model)
{
if (!ModelState.IsValid)
return View(model);
var item = repository.GetItem(id);
// throws error due to different context
item.Department = departmentRepository.GetItem(int.Parse(model.SelectedDepartment));
UpdateModel(item, "Item");
repository.Save();
return RedirectToAction("Member", new {id});
}
And the StaffMember
model contains...
public class StaffMember
{
public virtual Department Department { get; set; }
}
And the StaffViewModel
looks like this...
public class StaffViewModel : ViewModelBase<StaffMember>
{
public SelectList DepartmentList {get;set;}
public string SelectedDepartment {get;set;}
public StaffViewModel()
{
var departmentRepository = new DepartmentRepository();
DepartmentList = new SelectList(departmentRepository.GetCollection(), "ID", "Title", SelectedDepartment);
}
public StaffViewModel(StaffMember item) : this()
{
Item = item;
SelectedDepartment = Item.Department.ID.ToString();
}
public StaffViewModel(List<StaffMember> collection) : this()
{
Collection = collection;
}
}
In the database there is a int Department_ID
field which hooks up to the Department table.
I have a drop down in my view which looks like...
@Html.DropDownListFor(m => m.SelectedDepartment, Model.DepartmentList, "--Please Select--")
Apologies for the length of this question!