问题
I'm trying to subscribe my context to the OnjectMaterialized event following this, like so:
((IObjectContextAdapter)this).ObjectContext
.ObjectMaterialized += ObjectContext_OnObjectMaterialized;
But I'm using EF6 and the OnContextCreated method mentioned on that post does not exists in this version.
I tried subscribing the materialized event at the context constructor, but then, if the database is deleted (which we do often during integration tests), the event is no longer subscribed. We tried subscribing again after Database.Delete() but it doesn't work either.
So my question is, where should I properly subscribe the ObjectMaterialized event using Entity Framework 6?
回答1:
Could you simply subclass the context and subscribe to the event in the constructor? (I've done this and it works for my scenario. YMMV.)
回答2:
ModelContext modelContext = new ModelContext(); //Inherit DbContext
IObjectContextAdapter contextAdapter = modelContext;
ObjectContext objectContext = contextAdapter.ObjectContext;
来源:https://stackoverflow.com/questions/21664596/where-to-subscribe-to-objectmaterialized-using-ef6