Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DBContext Added/Attached Event?

EF 4.1 RC. I want to run some code after an entity has been added/attached to the DBContext. Is there an event for this (I can't find one). Basically I want to check if the added/attached entity is of a certain interface and if it is, do some stuff with it. Thanks!

like image 227
B Z Avatar asked Mar 23 '11 15:03

B Z


People also ask

Should DbContext be singleton or transient?

DbContext should not be used as a singleton because it is holding a connection object which cannot be used by multiple threads at the same time.

Why is DbContext not thread-safe?

This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread safe. When concurrent access goes undetected, it can result in undefined behavior, application crashes and data corruption.

Should DbContext be scoped or transient?

But if you use other injected services, with "transient" on the DBContext, every service gets his own instance of it. In order to avoid that you should always use "scoped" on the DBContext. Correct. Maybe there are cases in which you need a transient EF-Context - but usually you should stick to scoped.


1 Answers

To track changes to the Context you can use the ObjectStateManagerChanged event of the ObjectStateManager. To access the ObjectStateManager, you have to use the IObjectContextAdapter for casting the DbContext like

var contextAdapter = ((IObjectContextAdapter)dbcontext);            
contextAdapter.ObjectContext
              .ObjectStateManager
              .ObjectStateManagerChanged += ObjectStateManagerChanged;

Once you got the event, it fires every time the collection gets changed by adding or removing entities to the ObjectStateManager. To track the state of the entity, use GetObjectStateEntry() of the ObjectStateManager and use the Element of the CollectionChangeEventArgs param.

Combining both states of CollectionChangeEventArgs and ObjectStateEntry you can track, what is going on....

like image 130
KVerwold Avatar answered Oct 18 '22 15:10

KVerwold