This is based on an email I send my .NET team at work
Happy Friday,
Entity Framework Reverse POCO Generator
- https://visualstudiogallery.msdn.microsoft.com/ee4fcff9-0c4c-4179-afd9-7a2fb90f5838
- https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator
- https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator/wiki/Full-control-over-the-generated-code
I’d heard of this tool a few times, but never really checked it out until Rick suggested I send it out this week.
The idea is that you install an extension into Visual Studio, and it adds support for a custom T4 template that can connect to a database, read its schema, and generate all the EntityFramework plumbing you might need to interact with it.
I installed the extension and pointed a connection string at hobby database
I have on my local SQL Server Express. Then I added a New Item, finding the
reverse POCO item from online. As soon as I saved the new Database1.tt
file,
it generated Database1.cs
with a bunch of neat things in it:
An interface
1 | public interface IMyDbContext : System.IDisposable |
The name of the interface came from my connection string, which was MyDbContext
.
It actually generated two implementations: one was the expected default implementation using EF’s DbContext, but I was also pleasantly surprised to find a FakeDbContext that implemented the interface and could be used in unit tests.
Entity Classes
1 | [ ] |
Entity Configuration Classes
1 | // Users |
Since my DB was using a custom schema, I had to tweak one line in the
Database1.tt
file to not prepend schema names to the entity class
names. It prepends, by default, any schema name expect dbo
. But
finding and changing the option was straightforward and well documented.
This could be a great tool for if we get a project where we need to interact with a legacy database. Rather than hand-rolling all the entity classes, the Lead Dev could install this tool temporarily, run it, check in the output, and uninstall it. If the DB schema was pretty set in stone, and once you got the configuration the way you like, there would be no need to keep regenerating the code. We could save an awful lot of initial development and setup time with this.