阻止实体框架为导航属性插入值

man*_*der 14 c# wpf entity-framework

我正在使用Entity Framework 4.0处理WPF应用程序.当我尝试保存对象时,我得到了一个主键异常,但主键是一个AutoIncremented字段,我无法理解异常的原因.

所以在尝试了这个和那个,以及一些调试和使用SQL分析器后,我发现在插入我的对象之前,必须在父表中插入一条记录,因为我设置了该对象的导航属性.

所以关键是如果尝试插入Employee对象并将其部门设置为Employee.Department = deptObject,则将新记录设置为插入部门对象.

请告诉我某些导航属性对象不会插入数据库,任何属性或任何方法,Anything.

谢谢

Lad*_*nka 42

如果您错误地使用分离的实体,这就是EF的工作方式.我想你使用的是这样的东西:

var employee = new Employee();
employee.Department = GetDepartmentFromSomewhere(departmentId);

...

using (var context = new YourContext())
{
    context.Employees.AddObject(employee);
    context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

此代码编写了员工实体,添加了对现有部门的引用并将新员工保存到数据库中.问题出在哪儿?问题是AddObject不仅添加员工而是添加整个对象图.这就是EF的工作原理 - 你不能拥有对象图,其中部分对象连接到上下文而部分不连接到上下文.AddObject将图中的每个对象添加为新对象(新对象=在数据库中插入).因此,您必须更改操作顺序或手动修复实体状态,以便上下文知道该部门已存在.

第一个解决方案 - 使用相同的上下文来加载部门和保存员工:

using (var context = new YourContext())
{
    var employee = new Employee();
    ...
    context.Employees.AddObject(employee);

    employee.Department = context.Departments.Single(d => d.Id == departmentId);
    context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

第二种解决方案 - 将实体分别连接到上下文,然后在实体之间进行引用:

var employee = new Employee();
...

var department = GetDepartmentFromSomewhere(departmentId);

using (var context = new YourContext())
{
    context.Employees.AddObject(employee);
    context.Departments.Attach(department);
    employee.Department = department;

    context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

第三种解决方案 - 手动更正部门的状态,以便上下文不再插入它:

var employee = new Employee();
employee.Department = GetDepartmentFromSomewhere(departmentId);

...

using (var context = new YourContext())
{
    context.Employees.AddObject(employee);
    context.ObjectStateManager.ChangeObjectState(employee.Department, 
                                                 EntityState.Unchanged);
    context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

  • 在第三个解决方案中,如果Department对象还有另一种关系会发生什么?AddObject是否也标记了所有内容?你怎么能递归地标记回来不变? (3认同)
  • @Ladislav Mrnka +1为什么官方文件不能这么清楚! (2认同)