我正在使用Ninject
在我的网络Api存储库中注入IMainDataContext
,并且每次获得IMainDataContext
时,例如:
var _db = NinjectWebCommon.Kernel.Get<IMainDataContext>();
它会创建一个新图层(我猜这是正常行为),但是当我想在我的存储库之外调用SaveChanges()
时,例如在模型方法中,例如:
public void Save()
{
var _db = NinjectWebCommon.Kernel.Get<IMainDataContext>();
var project = _db.Projects.AsQueryable().SingleOrDefault(x => x.ID == this.ID);
_db.SaveChanges();
}
我收到此错误消息:
无法定义两个对象之间的关系,因为 它们附加到不同的ObjectContext对象
这是存储库:
private readonly IMainDataContext _db;
public CustomerRepository(IMainDataContext db)
{
_db = db;
}
public Customer GetByID(int ID)
{
return _db.Customers.AsQueryable().SingleOrDefault(x => x.ID == ID);
}
以下是API调用示例:
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.");
}
DBContext
中获得相同的Save()
?_customerRepo
注入初始DBContext
的地方吗?