1

During the life of my ObjectContext, I receive a message saying telling me that a new entity has been added to the data source by some other process (i.e. not tracked by my ObjectContext). How do I add this entity to my local ObjectContext without recreating it?

I've looked at ObjectContext.Refresh() but I'm not sure if this is the right way forwards.

djskinner
  • 7,517
  • 4
  • 46
  • 70
  • 1
    Some reading for you: Why is long living context bad - http://stackoverflow.com/questions/3653009/entity-framework-and-connection-pooling/3653392#3653392 and What is the purpose of self tracking entities - http://stackoverflow.com/questions/5091974/what-is-the-purpose-of-self-tracking-entities/5092097#5092097 . Be aware that STEs are available only in EFv4. – Ladislav Mrnka Apr 01 '11 at 19:02
  • See my response to @DevArt regarding STEs. – djskinner Apr 05 '11 at 08:01
  • Also, I long-running ObjectContexts are bad, what's the point in the DbSet.Local property. To me that implies that a long running object context is OK if we're going to bind it directly to a UI which may persist the lifetime of the application. http://blogs.msdn.com/b/adonet/archive/2011/02/01/using-dbcontext-in-ef-feature-ctp5-part-7-local-data.aspx – djskinner Apr 05 '11 at 08:02
  • yes context can live for longer time in winform or wpf application but it is still unit of work. – Ladislav Mrnka Apr 05 '11 at 08:08
  • So in the situation where the database changes whilst my local ObjectContext is still being used, how do I update it to reflect changes in the database? – djskinner Apr 05 '11 at 10:45

2 Answers2

1

If the entity is available in your code, use the Attach method.
In case this object is not available in your code, the solution is indeed to call the Refresh method with StoreWins RefreshMode for the collection the object was added into.
I recommend you to take a look at the Self-Tracking Entities as well.

Devart
  • 110,991
  • 22
  • 156
  • 173
  • I also pondered STEs but since I do have access to the ObjectContext on the same tier as my Entities, I didn't make much sense to use it. My understanding is that STEs are typically used to manipulate entities on one tier but persist those changes on another. – djskinner Apr 05 '11 at 07:58
  • @Daniel, you are correct, in this case STE does not provide any additional benefits. – Devart Apr 05 '11 at 11:06
  • I finally got it to work with a combination of Attach and Refresh – djskinner Apr 11 '11 at 10:06
0

Is the answer not in the question title - long running object contexts are not a good idea in EF. Ideally the OC should be kept alive for as short a time as possible.

Colin Desmond
  • 4,711
  • 4
  • 42
  • 65
  • 1
    I kind of expected this but how do I effectively keep track of a graph of entities detached from an object context? – djskinner Apr 01 '11 at 13:16