Home Dashboard Directory Help
Search

Entity framework: An object with the same key already exists in the ObjectStateManager by StefanOlson


Status: 

Active


0
0
Sign in
to vote
Type: Bug
ID: 456525
Opened: 5/22/2009 6:37:16 PM
Access Restriction: Public
0
Workaround(s)
view
0
User(s) can reproduce this bug

Description

I've just tried changing the target of my application to .net 4. The application works fine running in the .net framework 3.5 under Visual Studio 2010.

After changing the target I get this error message:
An object with the same key already exists in the ObjectStateManager. The existing object is in the Unchanged state. An object can only be added to the ObjectStateManager again if it is in the added state.

The code causing the problem is:
public EntityCollection<TourPropertyString> LoadedPropertyStrings
        {
            get
            {
                if (!PropertyStrings.IsLoaded && EntityKey != null && EntityState == System.Data.EntityState.Modified || EntityState == System.Data.EntityState.Unchanged)
                {
                    PropertyStrings.Load();
                }
                return PropertyStrings;
            }
        }

Unfortunately I can't duplicate this outside of my application, and changing it to use deferred loading caused the same problem to occur when the variable was accessed further out.

So I'll have to go back to the.net framework 3.5 in the meantime, if you have any ideas on how to isolate the problem more clearly for you please let me know.
Details
Sign in to post a comment.
Posted by Microsoft on 6/2/2009 at 7:50 PM
Hello Stefan,

Thanks for taking the time to give us the heads up on this issue. With the information you provided we were able to repro internally and found a bug on part of the code that deals with tracking relationships with entities as they get materialized. We have checked-in a fix for this bug and that fix should be included in the next prerelease version after Beta 1.

Sorry about the inconvenience and as soon as we are able to get the next public build out, it would be great to hear how EF 4 is working for your application.

Thanks,
Diego Vega, Program Manager
Entity Framework Team
Posted by StefanOlson on 5/30/2009 at 7:43 PM
Diego,

I've e-mailed a reproducible sample to you. I look forward to hearing how you get on with fixing it.

..Stefan
Posted by StefanOlson on 5/30/2009 at 5:35 PM
I've tried to reproduce the problem in an application using much the same code this time, still no luck.

However, I have commented out the dialog that displays and calls the function causing the problem, and now I have a line that says this:
ActiveProject.Targets.Load();
ActiveProject.CollectionObjects.Load();

The first line works fine, but the second line is displaying this exception:
The EntityCollection could not be loaded because it is not attached to an ObjectContext.

Stack trace is included below. I'll e-mail the model to you as I'd rather that it's not sticking around on some server.

I'll try and reproduce the problem under a virtual machine, but it may be later in the week. If you need any further information, that would help me avoid having to get it all tested under a virtual machine, let me know

...Stefan

at System.Data.Objects.DataClasses.RelatedEnd.ValidateLoad[TEntity](MergeOption mergeOption, String relatedEndName)
at System.Data.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)
at System.Data.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)
at System.Data.Objects.DataClasses.RelatedEnd.Load()
at TourEditor.MainWindow.MainWindow_Loaded(Object sender, RoutedEventArgs e) in [...]\MainWindow.xaml.cs:line 210
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
at MS.Internal.LoadedOrUnloadedOperation.DoWork()
at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at TourEditor.App.Main() in D:\projectswpf\TourEditor\TourEditor\obj\x86\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Posted by Microsoft on 5/30/2009 at 3:58 AM
Hello again,

By the way, if it is ok for you to provide your app and database as a working repro, let us know. Not sure if it will fit given that attachments here usually have size limit. So, feel free to email me at "diego dot vega at microsoft dot com".

Thanks,
Diego
Posted by Microsoft on 5/30/2009 at 3:50 AM
Hello Stefan,

Yes, the model (or the models if you have two different models and only one is failing) should be helpful. Can you add an attachment here?

Thanks,
Diego
Posted by StefanOlson on 5/29/2009 at 1:11 PM
Diego,

what is more interesting is that I created another application using the same model and basic assembly structure (with the edmx in separate assembly) and still couldn't repeat the problem! I'm happy to send the model to you if you think that will be of assistance.

...Stefan
Posted by Microsoft on 5/29/2009 at 10:18 AM
Hello Stefan,

Thanks for the stack trace, this is very useful! I have passed it to the team.

It is interestig that this is not failing in another app created from the same database. Is it possible for you to compare the two model files, or perhaps to send them our way so that we can do the comparison?

Thanks again,
Diego
Posted by StefanOlson on 5/28/2009 at 5:43 PM
Stack Trace:
at System.Data.Objects.ObjectStateManager.AddEntry(IEntityWrapper wrappedObject, EntityKey passedKey, EntitySet entitySet, String argumentName, Boolean isAdded)
at System.Data.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, String argumentName)
at System.Data.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach, HashSet`1 promotedEntityKeyRefs)
at System.Data.Objects.DataClasses.RelatedEnd.Add(IEntityWrapper wrappedTarget, Boolean applyConstraints, Boolean addRelationshipAsUnchanged, Boolean relationshipAlreadyExists, Boolean performNotificationOnly, Boolean allowModifyingOtherEndOfRelationship)
at System.Data.Objects.ObjectStateManager.AddEntityToCollectionOrReference(MergeOption mergeOption, IEntityWrapper wrappedSource, AssociationEndMember sourceMember, IEntityWrapper wrappedTarget, AssociationEndMember targetMember, Boolean setIsLoaded, Boolean relationshipAlreadyExists, Boolean inKeyEntryPromotion)
at System.Data.Common.Internal.Materialization.Shaper.HandleRelationshipSpan[T_SourceEntity](IEntityWrapper wrappedEntity, EntityKey targetKey, AssociationEndMember targetMember)
at lambda_method(Closure , Shaper )
at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Data.Objects.DataClasses.RelatedEnd.Merge[TEntity](IEnumerable`1 collection, MergeOption mergeOption, Boolean setIsLoaded)
at System.Data.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)
at System.Data.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)
at System.Data.Objects.DataClasses.RelatedEnd.Load()
at TourDB.DBClasses.PropertyStringGroup.get_LoadedPropertyStrings() in D:\projectswpf\TourEditor\TourDB\DBClasses\PropertyStringGroup.cs:line 71
at TourDB.DBClasses.PropertyStringGroup.GetPropertyStringByLang(Language language) in D:\projectswpf\TourEditor\TourDB\DBClasses\PropertyStringGroup.cs:line 85
at TourDB.DBClasses.PropertyStringGroup.GetStringByLang(Language language) in D:\projectswpf\TourEditor\TourDB\DBClasses\PropertyStringGroup.cs:line 97
at TourEditor.Converters.LanguageConverter.Convert(Object value, Type targetType, Object parameter, CultureInfo culture) in D:\projectswpf\TourEditor\TourEditor\Converters\LanguageConverter.cs:line 16
at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
at System.Windows.Data.BindingExpression.ScheduleTransfer(Boolean isASubPropertyChange)
at MS.Internal.Data.ClrBindingWorker.NewValueAvailable(Boolean dependencySourcesChanged, Boolean initialValue, Boolean isASubPropertyChange)
at MS.Internal.Data.PropertyPathWorker.UpdateSourceValueState(Int32 k, ICollectionView collectionView, Object newValue, Boolean isASubPropertyChange)
at MS.Internal.Data.PropertyPathWorker.RefreshValue()
at MS.Internal.Data.ClrBindingWorker.RefreshValue()
at System.Windows.Data.BindingExpression.UpdateTarget()
at OlsClassLib.OlsClassLibUI.BindableParameter.InvalidateBinding(BindableParameter param) in D:\projectswpf\OlsClassLib\OlsClassLibUI\BindableParameter.cs:line 153
at OlsClassLib.OlsClassLibUI.BindableParameter.<>c__DisplayClass1.<OnBindParameterChanged>b__0(Object , EventArgs ) in D:\projectswpf\OlsClassLib\OlsClassLibUI\BindableParameter.cs:line 100
at System.Windows.FrameworkElement.RaiseInitialized(EventPrivateKey key, EventArgs e)
at System.Windows.FrameworkElement.OnInitialized(EventArgs e)
at System.Windows.FrameworkElement.TryFireInitialized()
at System.Windows.FrameworkElement.EndInit()
at System.Xaml.Runtime.ClrObjectRuntime.InitializationGuard(XamlType xamlType, Object obj, Boolean begin)
at System.Xaml.Runtime.PartialTrustTolerantRuntime.InitializationGuard(XamlType xamlType, Object obj, Boolean begin)
at System.Xaml.XamlObjectWriter.Logic_EndInit(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.WriteEndObject()
at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)
at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter)
at System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)
at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
at System.Windows.FrameworkElement.ApplyTemplate()
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.Controls.Border.MeasureOverride(Size constraint)
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.Controls.Control.MeasureOverride(Size constraint)
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size constraint)
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.ContextLayoutManager.UpdateLayout()
at System.Windows.UIElement.UpdateLayout()
at System.Windows.Interop.HwndSource.SetLayoutSize()
at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value)
at System.Windows.Interop.HwndSource.set_RootVisual(Visual value)
at System.Windows.Window.SetRootVisual()
at System.Windows.Window.SetRootVisualAndUpdateSTC()
at System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight)
at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
at System.Windows.Window.CreateSourceWindowDuringShow()
at System.Windows.Window.SafeCreateWindowDuringShow()
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.Show()
at System.Windows.Window.ShowDialog()
Posted by StefanOlson on 5/28/2009 at 3:47 PM
Diego,

Yes it is being thrown from the line that loads the property strings.

I'll try and get you a stack trace and other info ASAP.

In the meantime, I can answer question number one which is that it's happening with unmodified entities. It's trying to load all of the information that it needs to display the user interface so nothing has been changed it's just the application startup.

I've tried to re-create the problem by using the same database in a separate application, but that so far hasn't been successful, so it must also be related to some of the other content that I'm loading.

...Stefan
Posted by Microsoft on 5/28/2009 at 3:23 PM
Hello Stefan,

Assuming the exception is being thrown in the line that loads the PropertyStrings collection, this behavior is certainly unexpected. Ideally, we should need to repro the issue here in order to investigate the cause, but here are a few things that may help:

1. Is this happening only with modified entities, unchanged entities, or both?
2. Can you please provide a stack trace?
3. Can you create some form of dump of the ObjectStateManager contents and of the database for the corresponding table at the moment of the failure?

Something that usually work in order to produce a smaller self-contained repro: take a snapshot of this table and related tables (2-levels deep should be generally enough) and the corresponding subset of the model.

Thanks,
Diego Vega, Entity Framework Team
Posted by Microsoft on 5/26/2009 at 3:01 AM
Thanks for the feedback. We are escalating this bug to the product unit who works on that specific feature area. The team will review this issue and make a decision on whether they will fix it or not for the next release.

Thank you,
Visual Studio Product Team
Sign in to post a workaround.