.NET Tips and Tricks

Blog archive

Free Tool: Let Entity Framework Generate Your Code-First Entities

Like everyone else, I like code-first Entity Framework (EF) development because it makes it so easy to integrate custom code with my EF entity code. But even in a pure code-first development, I suspect that most developers don't generate their databases from their entities because, most of the time, the database already exists (and, besides, the DBA won't let developers anywhere near the database's schema). That means you have to write all the repetitious property declaration in the entity objects to mimic the tables you'll be working with. Wouldn't it be nice if you had a tool to do it for you?

There are POCO generators out there, but you already have a tool: the ADO.NET Entity Framework database-first designer. The original versions of the designer generated a lot of peculiar code. More recent versions generate code that looks very much like the code you should write when doing code-first development. Why not take advantage of that?

Start by adding a new project to your solution. Then, to get the cleanest entity code possible, use NuGet to add Entity Framework 6.0 to the project. From Project | Add New Item, add the ADO.NET Entity Data Model and use the Wizard to work through adding the tables needed for your project. When you're done, close the designer to ensure that all the code for your entities is generated.

Now drill down beneath your edmx file in Solution Explorer to find your code files. You can skip the file called <NameOfYourModel>.cs/vb and <NameOfYourModel>.Designer.cs/vb (though, since the files have nothing in them, there's probably no harm in including them). Once you've found the files, still in Solution Explorer, drag them to your "real" data access project. Whenever you need to add another table you can return to the project with the designer and use it to generate your code for you.

This isn't a perfect solution: The edmx generator in EF 6.0 doesn't add any data annotations to the entities it generates, for instance (recently, I needed to add the Key attribute to the primary key properties on a project). This solution is also easier to implement in Visual Basic than in C# because of the embedded namespaces in the C# files. Even in C#, though, a project-wide search-and-replace will fix that problem. But by using a tool from the EF team to generate your EF code, you're guaranteed to be getting the best (and most up-to-date) EF code possible.

Posted by Peter Vogel on 12/04/2013


comments powered by Disqus

Featured

Subscribe on YouTube