Blog

All Blog Posts

Entity Framework Part 4: Reverse Engineer Code First

We continue our Entity Framework series. Read the previous posts at the links below: One barrier that developers face when trying to use an ORM on their project is supporting legacy databases, some of which may contain numerous tables and pre-existing relationships. It can be difficult to build your domain to properly fit the existing database schema—and even if that’s not an issue, it still would take a lot of time to manually generate all of the classes.

Entity Framework Power Tools contains a tool called Reverse Engineer Code First (RECF), which is a big help in these situations. In a nutshell, you point to an existing database and RECF generates your models, your mappings, and your data context. It even gives you the ability to customize how certain things are generated. Pretty slick!

If you’d like to follow along, you’ll need to create a database called HumanResources and run the following script to generate a schema and some test data:
Create Human Resources Entity Framework

I’ve also created a demo project here.

You’ll also want to download the Entity Framework Power Tool extension here.

Strategy

Before giving you the goods, I’m going to mention a few things to think about before proceeding. The main decision to make before going this route is determining how future database modifications will be made. Are they going to continue to be made outside of the realm of your application like they presumably are now? Or are you going to take control and have Entity Framework Migrations handle future changes?

In the former approach, you’re going to be limited by a few factors. First, you won’t be able to customize how RECF generates your model. RECF taps into Entity Framework to determine pluralization rules, which are far from perfect. For example, tables that end with “Status” are changed to “Statu.” Also, if you’re dealing with a database that uses crazy naming conventions, then you’re stuck with them. If you try to change them, and then need to run RECF again to get new database changes, your work will be overwritten.

If you’re able to manage future database updates, then you’re in good shape. You can follow the steps outlined in my previous blog post to hook up EF Migrations. The initial state of the database (what you pulled in with RECF) will be considered the first migration. After getting reconciled with EF Migrations, I would spend some fine tuning your mappings so you have a reasonable model to work with.

Let’s Get Started

Once Entity Framework Power Tools is installed (you may have to restart Visual Studio), you can right click on the project where you want the model and context to be created, go to the Entity Framework group, and click Reverse Engineer Code First. In the dialog, enter your database settings and click OK. That’s it. Wait a few seconds and you should have shiny new POCOs, mappings, and a Data Context.

Customizations

If you don’t like how certain things are mapped, you do have some limited options. If you right click on the project that contains your Data Context, go to the Entity Framework Group, and click Customize Reverse Engineer Templates, you will get three T3 templates generated for you that you can customize. Take note that these aren’t standard T3 templates so they’re not entirely flexible, but if you get creative you can solve a lot of problems.

There are a few issues I want to fix:
  1. I don’t like how a constructor overload is created in my Data Context that sets a Database Initializer.
  2. I want the main constructor in Data Context to pass in the name of my connection string to its base implementation.
  3. I do not want my POCOs to be partial by default.
  4. I don’t want all the method calls in my maps to be prefixed with “.this.” (OCD ALERT!)
For issue 1, I can simply delete lines 16-19 from the Context.tt file. For issue 2, I can change the value on line 22:
Reverse Engineer Code First Context

Finished product:
Reverse Engineer Code First After

For issue 3, I can simply remove the partial keyword on line 13 below:
Entity Framework Reverse Engineer Code First

And for issue 4, I can remove several instances of “this.” from below:
Reverse Engineer Code First Mapping template

After modifying our templates we can simply execute Reverse Engineer Code First like we did above. The tool will recognize that we have templates and will respect the change we made. You can view the finished product in the GitHub repository I linked above.

Conclusion

While there are some limitations to the Reverse Engineer Code First tool, it can be very useful if we have an existing database that we need to support. The good news is that this tool is open source, so if you run into a limitation that you just cannot live with, you can contribute to the project on Codeplex.

Like I mentioned, if you get creative you can add some useful stuff to your model. On a WPF project I worked with, we modified the templates to inherit from a base model class that contained OnProperyChanged logic. We also implemented validation classes for each entity using FluentValidation that used the Entity Framework engine to determine Required and Max Length validation rules.

There has been some chatter about the future of Reverse Engineer Code First, and it may find itself more of a first-class citizen of Entity Framework. It definitely could use more extensibility and configuration. In the next post in this series I will discuss some new features of the recently released Entity Framework 6. We will specifically take a look at the new Asynchronous features and how you can take advantage of them.

Update! Read part 5 on Entity Framework 6 features.