EF 6.x Code-First and Model-First with Trackable Entities 2.1

Until now Trackable Entities has required the Entity Framework Power Tools to reverse engineer Code-First model classes from an existing database.  But not long ago the Entity Framework team released the EF 6.x Tools for Visual Studio 2012 and 2013, so that you can use the same Entity Data Model wizard to generate context and entity classes using either the Code First or Model first approaches.  The advantage of the consolidated designer is that you can pick and choose which tables you want, versus generating classes for all the tables in your database – which could take an inordinate amount of time if your database has a lot of tables.

trackable-tools

When the tools were first released, the ability to customize the T4 templates used for generating Code First classes was undocumented.  However, the team eventually published an article on how to customize the templates, and I was able to include customized T4 templates in the Visual Studio samples and templates for Trackable Entities v2.1.  You can install Trackable Entities right from within Visual Studio, by selecting Tools, Extensions and Updates, and then searching for “trackable” in the Online Visual Studio Gallery.

trackable-online-gallery

Once you’ve installed Trackable Entities, simply create a new project and select either “Trackable Web API Application” or “Trackable WCF Service Application” from the Trackable category under Visual C#. (You can also select “Trackable Web API Application with Repository and Unit of Work”.)  Then right-click the Service.Entities project and select “Add New Item” from the context menu.  From the Data category select “ADO.NET Entity Data Model,” type a name for the model and click Add.  You will be presented with the Entity Data Model Wizard, where you can select an option to either create Code First classes or add an EF Designer model.

trackable-edm-choose

From there you can select which database objects to include.  If you chose the “Code First from Database” option, you’ll get context and model classes for the tables you selected.  If, on the other hand, you selected “EF Designer from Database,” you’ll get an Entity Data Model designer (backed by an EDMX file), with entities and associations representing a conceptual model of your database.  This is often referred to as the Model-First (or Database First) approach.

Trackable Entities v2.1 supports this strategy by providing a set of custom T4 templates for generating client and service entities based on the Entity Data Model depicted in the diagram.  Many developers prefer Model-First over Code-First because it is relatively easy to keep the model in sync with the database by right-clicking on the diagram and selecting “Update Model from Database.”  To generate trackable service entities from the EDM diagram, simply right-click on the design surface of the model and select “Add Code Generation Item”.

trackable-model-first-code-gen

From there you can select which database objects to include.  Then expand the Trackable, Data category and select “Service Trackable Entities EF 6.x Model First Generator”. For the name enter the same model name you specified when adding the EDM to your project.

trackable-model-first-generator

You will then be prompted to overwrite the existing .tt files in your project.  Respond “Yes” to overwrite the files, and you’ll get model classes which are customized to work with trackable entities.  These are identical to those generated for Code First using either the EF Power Tools or the EF 6.x Tools for VS.  For example, the Product entity appears as follows:

[JsonObject(IsReference = true)]

[DataContract(IsReference = true, Namespace = "http://schemas.datacontract.org/2004/07/TrackableEntities.Models")]

public partial class Product : ITrackable

{

    [DataMember]

    public int ProductId { get; set; }

    [DataMember]

    public string ProductName { get; set; }

    [DataMember]

    public Nullable<int> CategoryId { get; set; }

    [DataMember]

    public Nullable<decimal> UnitPrice { get; set; }

    [DataMember]

    public bool Discontinued { get; set; }

    [DataMember]

    public byte[] RowVersion { get; set; }

    

    [DataMember]

    public Category Category { get; set; }

    

    [DataMember]

    public TrackingState TrackingState { get; set; }

    [DataMember]

    public ICollection<string> ModifiedProperties { get; set; }

    [JsonProperty, DataMember]

    private Guid EntityIdentifier { get; set; }

}

Because the ADO.NET Entity Data Model designer is not compatible with the Client.Entities project, which is a Portable Class Library, you’ll need to add a .NET 4.5 Class Library project to the solution to generate client-side entities.  Simply repeat the process of adding a code generation item, but instead select “Client Trackable Entities EF 6.x Model First Generator”.  From the Client.Entities project you can then link to the model classes by right-clicking the project, then selecting Add Existing Item and choosing “Add As Link”.

Trackable entities contain three additional properties which enable tracking entity change-state across service boundaries: TrackingState (Unchanged, Modified, Added, Deleted), ModifiedProperties (a list of properties with changed values – used for partial table updates), and EntityIdentifier (a Guid used for correlating updated entities with original entities, so that changes can be merged back).  On the client, a ChangeTrackingCollection<T> automatically sets TrackingState when entities are added, modified or deleted, and caches deleted entities so they can be retrieved using the GetChanges method, along with other changed entities in the object graph – including child and reference entities.

A Portable Class Library is used for client entities, and for the client Nuget package, so that they can be used with any client, including WPF, Silverlight, Windows Store (tablet), Windows Phone, iOS and Android (via Xamarin).  And the libraries are designed in such a way that the client remains completely ignorant of how entities are persisted by the service.  Both XML and JSON serialization formats are supported, and there are mutli-project templates for both WCF and ASP.NET Web API, which allow you to implement an n-tier solution in a fraction of the time you would otherwise spend.  In addition, the templates implement best practices for stateless services which persist changes using the async capabilities of Entity Framework and WCF or Web API.  There is an ApplyChanges extension method on DbContext which walks the entire object graph in all directions to inform the EF context of changes, which are all persisted in a single transaction when SaveChanges is called.

About Tony Sneed

Married with three children.
This entry was posted in Technical and tagged , , , . Bookmark the permalink.

7 Responses to EF 6.x Code-First and Model-First with Trackable Entities 2.1

  1. Dhananjay says:

    “Add As Link” is not showing while adding new item

  2. Carl says:

    I installed the Trackable.Entities.EF.6 package into Visual Studio 2015, but I do not see any “Trackable Entities” choices in “New Item”. Does the package not work with VS 2015? I tried to see if there was any information at http://tonysneed.github.io/trackable-entities but it appears that site is no longer active.

    Thanks,
    Carl

  3. cnelson1 says:

    Ah, okay, I think I got it. Is the new “Code First from Database” choice in EDM Wizard equivalent to using the power tools to reverse engineer code first?

  4. cnelson1 says:

    Cool…thanks so much!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s