I’m having a hard time figuring out where to catch Entity Framework exceptions. I have SaveChanges and concurrency exceptions covered, however, I’m having a hard time finding a general rule to catch other exceptions (like timeouts because the server went down, or something).
I’m doing a Windows client application so exceptions cannot just spit out a “error” web page, they must give out options to continue the application (since you might have other windows opened in it, this is no simple app).
This was quite easy to figure out when using ADO.net directly: you’d trap exceptions on connection opening and query executing, however I’m not quite sure exactly when are connections opened and queries executed using EF4 (database-first in this case).
There are some simple cases (for example, when I actually run the enumerator on the IQueryable, by calling ToList or ToArray), but there are others which are not that easily found: for example, if I’m assigning an IQueryable to a WinForm control’s DataSource, depending on the control behaviour (which I’m not always controlling), it may or may not actually execute the query (some controls execute it upon calling DataBind later).
I know I could do this by trial and error (or just doing huge try/catch blocks), but I’m trying to figure out a more general way to do this.
I’ve tried searching for some onexception-like event on the ObjectContext, but haven’t found anything remotely near, and everything I find on the matter is about exceptions on SaveChanges and concurrency exceptions, which as I said, I have covered.
Any hints on where to go?
are you familiar with the concept of
unit of work? this typically defines the boundaries of when acontextbegins and ends. exception handling can then be placed in/around the unit of work to handle specific exceptions.here is just one idea.