当用户在表单上修改对象时,我想更新对象导航属性的非id字段。我的“Department”表的一些字段如下所示。。。
Id
DirectorId (object of Employee table)
NoOfEmployees
Location
和Employee表的字段如下所示:
Id
Name
Post
现在,当用户看到部门表的修改时,我还会显示员工的核心信息(职位为“主管”),在其组合框中选择当前主管,并在相应的文本框中显示所有相关信息等。一旦用户选择了不同的主管,相关字段也会相应更改。
现在我想要的是,如果用户此时更改了某些主管信息(例如姓名或年龄),这些更改应该反映在DB中,而不是强迫用户转到员工修改表并在那里进行更改。
我尝试了修改数据库对象的几个字段的简单方法,但当要修改的对象是导航属性(如上所述)时,这种方法不起作用。这是代码。。。
using (CompanyDBContext db = new CompanyDBContext() {
int id = ((Department)cbDept.SelectedItem).Id;
Department currentDept = db.Departments.Where(x => x.Id == id).First();
Department newDept = new Department();
newDept.Id = currentDept.Id;
newDept.Employee.Id = (int)cbDir.SelectedValue; // --> has no effect;
// raises NullRefException "Obj. ref. not set to an instance of an obj."
.....;
.....;
db.Entry(currentDept).CurrentValues.SetValues(newDept);
if (dirNameChanged) {
var director = new Employee() {
Id = currentDept.DirectorId,
Name = tbDirName.Text.Trim()
};
db.Employees.Attach(director); // --> raises exception
db.Entry(director).Property(x => x.Name).IsModified = true;
}
db.SaveChanges();
}
。Attach()方法引发InvalidOperationException异常,表示
Attaching an entity of type 'CompanyDatabase.Employee' failed because
another entity of the same type already has the same primary key value.
This can happen when using the 'Attach' method or setting the state of
an entity to 'Unchanged' or 'Modified' if any entities in the graph have
conflicting key values. This may be because some entities are new and have
not yet received database-generated key values. In this case use the 'Add'
method or the 'Added' entity state to track the graph and then set the state
of non-new entities to 'Unchanged' or 'Modified' as appropriate.
但使用Add()方法也会引发类似的异常。。。
有什么解决办法吗?
P、 美国国防部对象正在正常更改。更改Director对象也可以,即如果用户为部门选择一个新的Director。仅更改Director(Employee)的非id字段是一个问题。