我目前在 ASP.Net MVC 项目中使用存储库模式,并具有以下代码:
partial class Timesheet : ITimesheet
{
TimeSystemDBEntities _db;
public Timesheet()
{
_db = new TimeSystemDBEntities();
}
.
.
//More Methods
.
.
//Save WorkWeek to database
private void SaveWorkWeek(WorkWeek wk)
{
//Creating a new test context in attempt to resolve
//Error: “An entity object cannot be referenced by multiple instances of IEntityChangeTracker"
var testContext = new TimeSystemDBEntities();
var newWorkWeek = new WorkWeek();
var newStudent = new Student();
//Copy contents of wk to newWorkWeek
newWorkWeek.Students = newStudent.GetStudent(wk.Students.id);
newWorkWeek.MonDate = wk.MonDate;
newWorkWeek.MonHours = wk.MonHours;
newWorkWeek.TuesDate = wk.TuesDate;
newWorkWeek.TuesHours = wk.TuesHours;
newWorkWeek.WedDate = wk.WedDate;
newWorkWeek.WedHours = wk.WedHours;
newWorkWeek.ThursDate = wk.ThursDate;
newWorkWeek.ThursHours = wk.ThursHours;
newWorkWeek.FriDate = wk.FriDate;
newWorkWeek.FriHours = wk.FriHours;
newWorkWeek.TempSave = wk.TempSave;
testContext.AddToWorkWeek(newWorkWeek); //Exception thrown here
testContext.SaveChanges();
//Also tried
//_db.AddToWorkWeek(newWorkWeek); //Exception thrown here
//_db.SaveChanges();
//Also tried
//_db.detach(wk): //Different exception thrown here: Says it's not in ObjectStateManager
//_db.AddToWorkWeek(newWorkWeek);
//_db.SaveChanges();
//Also tried
//_db.detach(wk.Students): //Different exception thrown here: Says it's not in ObjectStateManager
//_db.AddToWorkWeek(newWorkWeek);
//_db.SaveChanges();
}
}
Student 和 WorkWeek 类分别是一对多的关系。我已经尝试了从分离到创建全新上下文的所有方法,如上面的示例代码,但无法保存对象。当我尝试分离时,它基本上说它不在 ObjectStateManager 中,我将其解释为没有可分离的内容,如果为真,这似乎与原始错误相矛盾。我不确定发生了什么,任何帮助表示赞赏。