Taking a cue from Julie Lerman and Scott Hanselman, I’ve decided to dub version 2.0 of my Trackable Entities framework, the “Ninja Edition.” After releasing v 1.0 six month ago, I received several constructive suggestions on the project discussion and issues forums, which highlighted features I needed to add in order to make Trackable Entities a viable alternative to the now defunct Entity Framework Self-Tracking Entities. Now that I’ve added these items, Trackable Entities lets you become an N-Tier Ninja.
Let me put it this way. With just a few clicks, Trackable Entities gives you a fully functioning, real-world N-Tier application, with client-side change tracking that is portable and platform agnostic (it can work on any client – from WPF and Windows Phone to iOS and Android), and server-side persistence of batch updates in a disconnected and stateless manner, within a single transaction and a single round trip. In other words, this thing is cool.
Can’t wait to get started? Check out the Online Tutorials, or have a look at the Getting Started Video to build a complete n-tier application with EF 6.1 and ASP.NET Web API 2.1 in less than 10 minutes.
Aside from the coolness factor, what makes Trackable Entities a killer framework, is that it comes as a Visual Studio Extension. To get it from within Visual Studio, all you have to do is install it from the Tools, Extensions and Updates menu. This will give you a number of Trackable Entities project templates.
Once you click on one of these babies, you get a mulit-project Visual Studio solution. This in itself is an incredible time-saver. All of the NuGet packages are there. All of the project references are correctly set. Customized T4 templates are inserted and ready to go.
The next step is to reverse engineer an existing database into entities and mapping classes. For this aspect, we leverage the Entity Framework Power Tools. (I’m planning to replace this in the near future with the EF 6.1 Tools for Visual Studio, which also come with VS 2013 Update 2.) The reason for this is that it’s easy to customize entity code-generation by modifying a set of T4 templates. On the client side, the entities are data-binding friendly and they play nice with the change tracker. On the server side, the templates generate classes that are much simpler, without concern for change tracking or data binding. Because the classes are persistence ignorant POCO’s (Plain Old CLR Objects), they’re ideal for use with Domain Driven Design Patterns (such as Repository and Unit of Work).
What this separation between client and server entities means is that the service does not have to worry about how change tracking takes place on the client. All it cares about are two little properties: TrackingState (Unchanged, Modified, Added or Deleted) and ModifiedProperties (which properties have been changed). This is essentially what sets Trackable Entities apart from its evil twin, Self-Tracking Entities. In order to apply changes to an Entity Framework DbContext, we don’t need to know anything about original property values, and all the change-tracking logic is encapsulated on the client, by adding the Trackable Entities Client NuGet package.
Then there’s hassle-free serialization. Trackable Entities sets everything up so you don’t have to worry about tweaking configuration settings or attaching the correct attributes. This is worth mentioning because by default Entity Framework favors the least common use-case, which a client communicating directly with a database via EF. DbContext is configured to use dynamic proxies for lazy loading, and these are not serializable. Trackable Entities, on the other hand, provides a DbContext class with proxy generation turned off, and entities are decorated with both JsonObject and DataContract attributes, so that cyclical references do not break the serializer.
The other thing that makes n-tier just plain hard is the Entity Framework API for persisting changes in a disconnected fashion. Julie Lerman and Rowan Miller discuss this in their excellent DbContext book, but it remains a complex problem to solve, especially when it comes to dealing with many-to-many relationships. But this is where Trackable Entities shines. All you have to do is write one line of code: DbContext.ApplyChanges. Pass in one or more entities, and Trackable Entities will walk the entire object graph in all directions, correctly setting entity state. It uses recursion to traverse the graph and can apply a change several layers deep. And here’s the kicker: it knows how to deal with many-to-many relationships. This is a feature I added to version 2.0, and it uses the metadata workspace to reflect over the conceptual model and add or remove entities from the M-M relationship without inserting or deleting the entities themselves.
Another cool feature I added to v 2.0 is an extension method to DbContext called LoadRelatedEntities. This is one I’m especially proud of. It obviates the need to call LoadProperty on ObjectContext, which can be quite inefficient and can only be executed synchronously. The reason you may need to load properties is to set reference properties on added entities. For example, you create a new order with details, and you want to return the inserted order with Customer set on each order and Product set on each order detail. What makes LoadRelatedEntities so gnarly (to use surfer-speak) is (a) it traverses the object graph, so you only have to call it once, (b) it fetches batches of entities by dynamically constructing Entity SQL statements, and (c) it can be executed asynchronously, utilizing EF 6’s async capabilities.
After performing updates, it is important to return updated entities to the client, so that entity properties are populated with database generated values, for example, identity keys and concurrency tokens. The trick is knowing how to merge changes back into the original objects, when those objects do not contain any metadata concerning primary keys. The solution is to use a unique identifier that allows you to correlate each updated entity to the corresponding original entity. In v 2.0 I added a new MergeChanges method that does precisely this. Now you can update a collection of entities bound to a data grid without affecting the order or messing up the data bindings.
There are separate installers for Visual Studio 2012 and 2013, with limited support for .NET 4.0. The VS extension includes multi-project templates for both WCF and ASP.NET Web API, with item templates that provide both WCF service types and Web API controllers. And wherever possible operations and actions are asynchronous.
Lastly, the icing on the cake is full support for domain driven design with repository and unit of work patterns. A separate template gives you a multi-project solution, with interfaces separated cleanly from implementation, so that you have complete independence from the underlying persistence framework, enabling you to future-proof your app against potential obsolescence and, should it become necessary, swap out EF for something else.
The beauty of Trackable Entities is that you get all this goodness for free, and you can accomplish in minutes what it would otherwise take hours or days to pull off. To get started you can go through one of the Online Tutorials (Web API, WCF, or Repo / Unit of Work), or take a look at the Getting Started Video, to build an end-to-end n-tier application in no time with Trackable Entities, Entity Framework, and ASP.NET Web API or WCF. Enjoy!