O'Reilly logo

Programming Entity Framework, 2nd Edition by Julia Lerman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required