EF 4.1 RC. I want to run some code after an e开发者_运维问答ntity 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!
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....
Unfortunatelly there are no such events available and there are no extension points to add such events. That is in my opition one of the biggest EF failure. The extensibility = zero.
The only thing you can do is override SaveChanges
and before executing base.SaveChanges
use ChangeTracker
to get all attached and added entities of your type and execute your logic. But it is not the same as triggering an event when attaching or adding an entity to the context.
Handle the CollectionChanged event for the relevant DbSet's Local property (ObservableCollection).
Check the added/attached entity object's DbEntityEntry's state for added or unmodified for added/attached, respectively.
DbSet.Local property: http://msdn.microsoft.com/en-us/library/gg696248(v=vs.103).aspx
DbContext.Entry method: http://msdn.microsoft.com/en-us/library/gg696578(v=vs.103).aspx
精彩评论