I have read the various posts regarding this error message and have typically avoided this problem in the past, but still haven't been able to figure this one, why am I getting this error:
System.NotSupportedException: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.
On this code:
Public Overloads Function insertRow(ByVal areaOfLaw As AreaOfLaw, ByVal accomplishment As Accomplishment) As Boolean
Using lcfDataContext As New LCFDataContext()
Dim tempArea As AreaOfLaw = lcfDataContext.AreaOfLaws.Where(Function(x) x.Id = areaOfLaw.Id).SingleOrDefault()
Dim alreadyExists As Boolean = False
If tempArea Is Nothing Then
tempArea = areaOfLaw
lcfDataContext.AreaOfLaws.InsertOnSubmit(tempArea)
End If
Dim tempAccomplishment As Accomplishment = _
lcfDataContext.Accomplishments.Where(Function(x) x.Id = accomplishment.Id).SingleOrDefault()
If tempAccomplishment Is Nothing Then
tempAccomplishment = accomplishment
lcfDataContext.Accomplishments.InsertOnSubmit(tempAccomplishment)
End If
Dim tempAccomplishmentAreaOfLaw = lcfDataContext.AccomplishmentAreaOfLaws.Where(Function(x) x.AreaOfLaw.Id = tempArea.Id And x.Accomplishment.Id = tempAccomplishment.Id)
If tempAccomplishmentAreaOfLaw.Count = 0 Then
Dim accomplishmentAreaOfLaw As New AccomplishmentAreaOfLaw(tempAccomplishment, tempArea, SessionConstants.Username)
lcfDataContext.AccomplishmentAreaOfLaws.InsertOnSubmit(accomplishmentAreaOfLaw)
Else
alreadyExists = True
End If
If alreadyExists = False Then
Try
lcfDataContext.SubmitChanges()
Return True
Catch ex As Exception
Return False
End Try
Else
Return True
End If
End Using
End Function
Specifically at this line:
Dim tempAccomplishmentAreaOfLaw = lcfDataContext.AccomplishmentAreaOfLaws.Where(Function(x) x.AreaOfLaw.Id = tempArea.Id And x.Accomplishment.Id = tempAccomplishment.Id)
In this function, an areaOfLaw is always going to exist because it is selected from a dropdown menu. I was just copying a template I got from here, but I query it using this datacontext to avoid the error I am getting, and the accomplishment I pass in is always going to be new (this is being called from a page where you create accomplishments), and the values are populated 100% from form values, I don't populate any linked objects within in with objects I got from another dc. Im further confused because I thought this error only pops up when you try to save an object using a different context than what you queried it from, but I don't appear to be doing that here, all queries and writes are from this one data context.
Why is this error occurring??