DBContext Added/Attached Event?

ⅰ亾dé卋堺 提交于 2019-11-28 11:22:24

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.

KVerwold

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

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

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