I am using Ninject
to inject IMainDataContext
around my Web Api repositories and every time I get IMainDataContext
, e.g.:
var _db = NinjectWebCommon.Kernel.Get<IMainDataContext>();
it creates a new layer (which I guess is a normal behavior), but when I want to call SaveChanges()
outside of my repositories, e.g. within model methods, like:
public void Save()
{
var _db = NinjectWebCommon.Kernel.Get<IMainDataContext>();
var project = _db.Projects.AsQueryable().SingleOrDefault(x => x.ID == this.ID);
_db.SaveChanges();
}
I get this error message:
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects
Here is repository:
private readonly IMainDataContext _db;
public CustomerRepository(IMainDataContext db)
{
_db = db;
}
public Customer GetByID(int ID)
{
return _db.Customers.AsQueryable().SingleOrDefault(x => x.ID == ID);
}
Here is an example API call:
public IHttpActionResult ChangeGroups(int projectID, ProjectChangeGroupsDto model)
{
var groupIDs = model.GroupIDs;
// Get customer from Repository
var _customer = _customerRepo.GetByID(this._customerID);
var project = _customer.GetProjectByID(projectID);
if (project == null)
{
return BadRequest("Project does not exist.");
}
if (groupIDs.Where(grpID => !_customer.Groups.Any(grp => grp.ID == grpID)).Any())
{
return BadRequest("Supplied list is invalid.");
}
project.Groups.Clear();
_customer.Groups.Where(grp => groupIDs.Any(grpID => grpID == grp.ID))
.ToList()
.ForEach(grp =>
{
project.Groups.Add(grp);
});
project.Save();
return Ok("Groups have been added.");
}
Questions
- Is it possible to get same
DBContext
inside the model methodSave()
? - Is there a better approach to this? (should I just put all my entity updates within
_customerRepo
where the initialDBContext
has been injected)