Chapter 22. Handling Exceptions

Things can go awry in many ways when you’re querying or updating entities. 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 compilation 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. When one of these exceptions is raised, it is up to your code to handle it.

In this chapter, we’ll look at exceptions that are unique to the Entity Framework and how to handle them. Some exceptions are Entity Framework-specific exceptions, and others are .NET exceptions caused by faulty operations when using the Entity Framework.

Note

You should strongly consider exception handling for any application you write. If this is a new topic for you, plenty of resources are available on the Web, in the MSDN documentation, and in a variety of books to teach you accepted patterns and practices for implementing exception handling in .NET.

Preparing for Exceptions

In Object Services, you can get exceptions ...

Get Programming Entity Framework, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.