DBContext Added/Attached Event?

时间秒杀一切 提交于 2019-11-27 03:27:28

问题


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!


回答1:


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.




回答2:


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....




回答3:


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



来源:https://stackoverflow.com/questions/5407860/dbcontext-added-attached-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!