Chapter 18. Handling Entity Framework Exceptions
Things can go awry in many ways when you’re querying or updating entities. The Entity Data Model (EDM), for example, could have a problem that the validator fails to detect but that makes it difficult for a query to be compiled. You might attempt to save entities to the database that are missing related data—a reservation without a trip, perhaps, or a reservation without a customer. The database might have a constraint that is not reflected in the model; if a user saves data that breaks the rule of the constraint, the database will throw an error. Or someone may have modified or even deleted a record while another user was editing it.
The Entity Framework includes a specialized set of exceptions for capturing problems like these that arise during query and command execution.
In your application, you should embed each query execution or call
you make to SaveChanges
in some sort of
mechanism for catching these exceptions, most likely a Try
/Catch
block. When one of these exceptions is raised, it is up to your code to
handle it.
In this chapter, we’ll look at exception handling that is unique to the Entity Framework. Some exceptions are Entity Framework-specific exceptions, and others are .NET exceptions caused by faulty operations in the Entity Framework. You’ll also spend a good deal of time focusing on concurrency exceptions, which are raised by a database conflict is caused when multiple users edit the same data concurrently.
Note
You ...
Get Programming Entity Framework now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.