0

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

  1. Is it possible to get same DBContext inside the model method Save()?
  2. Is there a better approach to this? (should I just put all my entity updates within _customerRepo where the initial DBContext has been injected)
skmasq
  • 4,470
  • 6
  • 42
  • 77
  • It should be possible to have a [context per request](http://stackoverflow.com/q/11921883/861716) and you shouldn't use Ninject as a service locator, but use constructor injection. – Gert Arnold Feb 12 '15 at 21:21
  • @GertArnold It worked. Thank you for reference. I used `InRequestScope()` – skmasq Feb 12 '15 at 21:37

0 Answers0