Databases Reference
In-Depth Information
ValidationException , preventing the SaveChanges method from saving the changes to
the database.
NOTE
The BeforeSaveChanges method intentionally excludes deleted entities from validation
because most rules would not be applicable and cause unnecessary errors. Chapter 9,
“Implementing Business Logic,” includes a detailed discussion of this topic.
Customizing Entity Framework Code Generation
The UnleashedObjectContext class shown in Listing 8.1 is available with the sample
project accompanying this topic. It is defined in a separate assembly called
Unleashed.EntityFramework and includes a substantial amount of general-purpose code
that any Entity Framework application could reuse. Although you could simply copy its
code, you might want to have the Entity Framework context class, such as the
NorthwindEntities in the ongoing example, inherit from it instead. This helps to keep the
infrastructure code out of the application, which was beneficial even with the sample
entity model discussed in this topic.
With the database-first and model-first approaches to Entity Framework model develop-
ment, the NorthwindEntities class is generated by the Entity Designer. By default, it inher-
its from the ObjectContext . You cannot change its declaration directly because any
modifications would be lost next time the code is regenerated. Instead, you need to
change the code generator itself. This section shows how you can replace the built-in
Entity Framework code with a text template that can be customized to change how the
code is generated.
NOTE
Customizing the code generated by Entity Framework can solve other common prob-
lems as well. For instance, Chapter 9 relies on this approach to provide information
about default values of entity properties to Dynamic Data.
Replacing Built-in Code Generator with Text Template
To replace the built-in code generator the Entity Designer uses, right-click the design
surface and select Add Code Generation Item from the context menu. In the Add New
Item Dialog (see Figure 8.1), choose the ADO.NET Entity Object Generator and give it a
name matching the name of the EDMX file.
 
 
Search WWH ::




Custom Search