Programming Entity Framework: DbContext by Julia Lerman and Rowan Miller
I’d been to a couple of talks on the Entity Framework, but I had never really used it. A colleague at work lent me this book, which focuses on the code first aspect of the Entity Framework by way of the DbContext, a type based on the original ObjectContext.
The DbContext API has really good support for Code First development – using convention over configuration it is really easy to define some plain old C# classes (POCOs), and create some tables in a database that store them.
Making an instance of the context, we can create instances of the domain classes and add them into the context, which allows the context to track them and subsequently persist them when a call to SaveChanges is made. The book has a whole chapter in the change tracking that the context does, covering how you can determine if an object has been modified and change the tracked state, and how you can restore objects to their initially tracked values.
Without any configuration the Entity Framework connected to the local SqlExpress instance, and created a database and tables of the appropriate name.
We can use the server object explorer in Visual Studio to look at the database changes that have been made.
The book covers the three ways that the Entity Framework handles loading of cross-table references. It can do this eagerly, on demand or lazily (assuming that the class is defined in a way that allows a proxy to be generated). The Include form in the following query forces the loading of the Data property of the class. The API allows the lambda syntax way of naming a property which is friendly to refactoring tools, though it also offers an overload that takes a string.
The queries, implemented via Linq to Entities, allow you to write queries that can even include some standard SQL operators.
In order to write multiple tier applications you often need to run a query, take the objects in the result and ship them off to another tier for processing. After processing, you want to reconcile the changes made by the processing into the retrieved model so that it can be persisted back to the database. The book has an entire chapter on how you can go about this. The DbContext API supports Attaching and Detaching instances from the context, but also allows you to manually modify the data in the change tracking API to control whether properties are written back to the database.
The book also has a chapter on the .NET 4 ValidationAttribute and the IValidateObject interface that supports data validation. These items are explained and then there are loads of practical examples of their use.
The book is fairly short at 220 pages, but gives lots of practical information and allows you to dive straight into the Entity Framework.