I'm deep somewhere in the Business layer in a debugging session in Visual Studio trying to figure out why an Entity is behaving strangely when trying to persist the changes.
It would really be helpful to get a reference to the DbContext this Entity belongs to, at this point in the call stack.
I.e. to see what the state is of this Entity is (Unchanged, Modified, etc).
So I'm looking for a helper method like this:
var db_context = DbContextHelpers.GetDbContext(entity);
// after that I could do something like this
var state = db_context.Entry(entity);
I can use this stuff in the Immediate window during debugging.
Anyone any suggestions?
Extra notes
The Entity must be aware of the DbContext
somewhere, because it is using it for lazy loading navigation properties?
EntityState
of the model that I'm looking at - say 12 layers deep within the Business layer. It has no access to the DbContext that has been created at a completely other part of the code.DbContext
so it is available where you need it to be available? If you're developing an ASP.NET application you could put it inHttpContext.Current.Items
or keep it around as a thread-local, you could event simply assign theDbContext
to some static field in some static class. In some cases, you could do that in the immediate window of the VS debugger, especially putting something into theHttpContext
is easily done there. Be sure to remove the hack once you're done debugging though :-).DbContext
around and enable it just when you're debugging - via DI or a config flag for example. I'm unsure whether retrievingDbContext
for an entity object is possible, you could do a deep dive into the object using the VS debugger's watch functionality, maybe you can find some reference that you could extract via reflection or so.