Print Page | Close Window

Entity exists when adding

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=2771
Printed Date: 25-Jan-2026 at 11:47am


Topic: Entity exists when adding
Posted By: GeorgeB
Subject: Entity exists when adding
Date Posted: 16-Jun-2011 at 11:09am
Hi
 
I'm using DevForce 6.1 with Silverlight.
 
I have a single instance of EntityManager. I create a new entity, add it to the manager and in some instances I get this error:-
 
An entity with this key: TrackingEvent: -100 already exists in this EntityManager
 
In my repository I have (nothing really fancy - I'm using INT in SQL Server as a IdentityColumn)
 public TrackingEvent CreateTrackingEvent()
        {
            var aTrackingEvent = Manager.CreateEntity<TrackingEvent>();
            Manager.GenerateId(aTrackingEvent, TrackingEvent.PropertyMetadata.TrackingEventID);
            Manager.AddEntity(aTrackingEvent);
            return aTrackingEvent;
        }
Once I've assigned values to all the fields, I do a SaveAsync().
It's possible that the CreateTrackingEvent may get called at the same time but I can't stop that (nature of the application). 
Surely between the GenerateId and AddEntity, the EM can keep the ID's unique? 
Do I need create my own IdGenerator?
Thanks
George



Replies:
Posted By: kimj
Date Posted: 16-Jun-2011 at 5:18pm
Hi George,
 
The EntityManager is not designed to be thread safe, so if you are finding that the CreateTrackingEvent can be called simultaneously from two separate threads then you should lock around the logic in the method.  Eg,
 
lock (_aLockObject) {
  ... create and add entity
}
 
If that doesn't fix the problem, then it's not a threading issue and we'll need to get more information on what's going on within the application.
 
 


Posted By: GeorgeB
Date Posted: 20-Jun-2011 at 10:21pm
Hi Kim
 
Okay totally my problem.
 
When testing with single a record coming in everything worked but when multiple records were coming in (and they could be duplicated), I was doing an async check to see if the record already existed, it was possible in some cases for me to be adding a new record whilst still waiting for the first check to come back.
 
My system is a lot more complex that what I have described above, but that is the big picture.
 
Thanks for the help.
 
Kr
George



Print Page | Close Window