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!
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.
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.
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.
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....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With