7

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?

Community
  • 1
  • 1
fdiaz
  • 71
  • 1
  • 4
  • As I guess I would say they abstracted it to the [`Interception`](https://entityframework.codeplex.com/wikipage?title=Interception) API. But i would ask what the root of the problem is and maybe there's a better way to tackle it than subscribing to an event. – Brad Christie Mar 03 '14 at 15:18
  • @BradChristie I have a property in one of my POCO classes that is not mapped and I want to build it and make it available as soon as possible (it loads other entities from the local context). I had assumed the sooner would be on ObjectMaterialized. There are other ways to do all this of course, but since the event is there, I wanted to see if it could be done this way. It works, except for the issue mentioned above when deleting the database, then the event is lost until another context is instantiated. – fdiaz Mar 11 '14 at 07:37

2 Answers2

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

wintermute
  • 186
  • 6
0
ModelContext modelContext = new ModelContext(); //Inherit DbContext
IObjectContextAdapter contextAdapter = modelContext;
ObjectContext objectContext = contextAdapter.ObjectContext;
Termininja
  • 6,620
  • 12
  • 48
  • 49
shnahmet
  • 26
  • 1