title: Active Record with Entity Framework
body: <p>I'm working on a project that was built using ADO.NET (raw sql) and Active Record pattern.  I am slowly moving it away from ADO.NET to Entity Framework Code First 4.3.</p>
  
  <p>Here is an example of the pattern.  The interface is a static Load and an instance Save (and Delete -- not shown).</p>
  
  <pre><code>Public Class Part
      Public Property Id as Integer
  
      Public Shared Function Load(_id As Integer) As Part
          Using context As New DataContext()
              Return context.Find(_id)
          End Using
      End Function
  
      Public Sub Save()
          Using context As New DataContext()
              If Id = 0 Then
                  context.Parts.Add(Me)
              Else
                  context.Entry(Me).State = Data.EntityState.Modified
              End If
  
              context.SaveChanges()
          End Using
      End Sub
  End Class
  </code></pre>
  
  <p>I realize Active Record is not ideal for EF but I'd like to make it work to remove all of the ADO.NET code while not touching the rest of the code.</p>
  
  <p>This mostly works, but I've run into an issue I don't know how to solve.  In order to keep Foreign Keys in sync we handle it like such:</p>
  
  <pre><code>Public Sub Save()
      ParentPart = Part.Load(ParentPartId)
      ChildPart = Part.Load(ChildPartId)
  
      Using context = New iTracContext()
  
          If bid = 0 Then
              context.BillOfMaterials.Add(Me)
          Else
              context.Entry(Me).State = Data.EntityState.Modified
          End If
  
          context.SaveChanges()
      End Using
  End Sub
  </code></pre>
  
  <p>This makes sure EF doesn't complain that we have non-matching relationships -- the Id always wins.</p>
  
  <p>The issue is that its throwing an exception now when I save.</p>
  
  <blockquote>
    <p>An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.</p>
  </blockquote>
  
  <p>This is thrown from the line:</p>
  
  <pre><code>context.Entry(Me).State = Data.EntityState.Modified
  </code></pre>
  
  <p>How is anything in the <code>ObjectStateManager</code> for this context?  It is brand new and should be empty, no?</p>
  
  <p>If I remove the two <code>Part.Load(...)</code> lines it works fine.</p>
  
  <p>Is there some type of change tracker that lives outside the context that I'm not aware of?  That seems like it would kill any attempt at the Active Record pattern.</p>
  
  <p>I'm also open to any suggestions on how to make Active Record work with EF.  The <code>context.Entry</code> line is terrible but I don't know what else to do.</p>
  
  <p>Telling me not to do Active Record isn't helpful, but feel free.</p>