Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is the way how EF works if you incorrectly use detached entities. I suppose you are using something like this:</p> <pre><code>var employee = new Employee(); employee.Department = GetDepartmentFromSomewhere(departmentId); ... using (var context = new YourContext()) { context.Employees.AddObject(employee); context.SaveChanges(); } </code></pre> <p>This code prepared employee entity, added reference to existing department and saved new employee to the database. Where is the problem? The problem is that <code>AddObject</code> doesn't add only employee but whole object graph. That is how EF works - you cannot have object graph where part of objects are connected to context and part of not. <code>AddObject</code> adds every object in the graph as a new one (new one = insert in database). So you must either change sequence of your operations or fix state of entities manually so that your context knows that department already exists.</p> <p>First solution - use the same context for loading department and saving employee:</p> <pre><code>using (var context = new YourContext()) { var employee = new Employee(); ... context.Employees.AddObject(employee); employee.Department = context.Departments.Single(d =&gt; d.Id == departmentId); context.SaveChanges(); } </code></pre> <p>Second solution - connect entities to the context separately and after that make reference between entities:</p> <pre><code>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(); } </code></pre> <p>Third solution - correct state of the department manually so that context doesn't insert it again:</p> <pre><code>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(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload