Part 5: Use an ORM to Create Your Data Layer

In this last part of the series, we talk about how to use ORMs to speed up the creation of your data access layer.

Written by Jonathan "JD" Danylko • Last Updated: • MVC •
Use ORMs to Create a Data Layer Quicker

We programmers are a lazy bunch.

We always try to find ways to make our life easier by using the computer to do the heavy lifting for us. Heck, that was the reasoning for this whole series.

For the last part of this series, we'll cover a couple tips on how to maximize a particular ORM (specifically Entity Framework) to quickly generate your data layer for your application.

Why use an ORM?

So everyone needs a persistent storage for their application, right? So why not use an ORM. Well, there are some advantages and disadvantages. 

Using an ORM (Object-Relational Mapping) significantly reduces the amount of time it takes to create a data access layer for any application. That's the advantage.

One disadvantage is that you may need to put time in up-front to figure out the details of how that ORM actually works. Each ORM is different. For example, NHibernate uses XML mapping files while Entity Framework is starting to move towards a Code-First mentality (starting in EF 7).

To be honest, I find the advantages outweigh the disadvantages.

Entity Framework

As if you didn't know, my ORM of choice is Entity Framework. I have worked with a select few ORMs and I can just hear some developers asking why Entity Framework. Here are my reasons:

  1. I've been using Entity Framework since 2008 when it was released. Over time, I've worked out the kinks and kicked the tires enough to know how it works and how to optimize it.
  2. It comes out of the box with Visual Studio.
  3. DanylkoWeb is running on it.
  4. It generates a Data Access Layer in no time flat (when using an existing database) with plenty of extensibility.
  5. It uses T4 to write out the Unit of Work DbContext. Definitely a plus if I need to modify the T4 template (If interested in T4, I would also recommend the article about revving up your code with T4 in this series).

With that said, I've talked enough about Entity Framework. Let's dig into it and learn some tips and tricks to speed your development!

Reverse Engineer Database-First into Code-First

We will cheat a little bit here and use an existing database. The whole idea here is to create almost 80-90% of your data access layer with little to no effort.

You will also need an extension for this little trick: Entity Framework Reverse POCO (Plain Old CLR Object) Generator. You can find this extension at this link or use Visual Studio's Extension Manager and install it from the Online section.

For those who have used the Database-First option before, you'll appreciate this trick. You won't have to look at that mapping connection string in the web.config ever again.

Once you have the extension installed and you have a database, you are ready to generate your Code-First entities. I place mine in a folder called GeneratedClasses.

I created my folder called GeneratedClasses off the root. Now, Right-Click -> Add -> New Item. At this point, I always use the Online category in the accordion menu on the left. Just type in the name of the extension in the top-right hand corner and you'll find it.

Give your T4 template a name (as you can see I called mine FaqModel.tt from our ThinController project) and click Add.

Entity Framework Reverse POCO Generator

Three files should be in your GeneratedClasses folder: FaqModel.tt (or whatever you called it), EF.Reverse.POCO.Core.ttinclude, and EF.Reverse.POCO.ttinclude. Only work with your model.tt file. Leave the other two alone unless you really want to get into T4. :-)

Open your FaqModel.tt template.

FaqModel.tt Results

I know it doesn't look like much, but we are just focusing on the parameters of the T4 template for right now.

Expand the outline and view the parameters.

Reverse POCO Settings

The primary settings I focus on are:

  • DbContextName - Custom name for your Context.
  • ConnectionStringName - This is a plain old ConnectionString in your web.config, NOT an EF Mapping Connection String.
  • MakePartialClasses - I make this true to hold our business logic in another location.
  • GenerateSeparateFiles - Just a general note, I know I should make this true, but I like it self-contained in one file in one directory that I don't touch.

If you scroll down a little further, there are a couple other parameters that I set. Scroll down and you'll see:

  • SchemaName - I do partition some of my tables into appropriate schemas so if I only wanted to generate entities based on one schema, I would enter the schema name here.
  • PrependSchemaName - I always set this to false unless I have an entity naming conflict.

Once these are entered and you have a legitimate ConnectionString, press Ctrl-S and your FaqModel.tt will generate the classes underneath the T4 template for you to use in your app.

Create your Business Logic

When you have your entities generated, you need to focus on the business logic for each one (if any). I know what you're thinking. How do we add business logic to a class that is automatically generated?

Remember the partial setting in the T4 template? When we set that to true, it set the classes to partial. Now that you have partial classes, you can add any type of business logic to an existing entity in another directory.

Why are my partials grayed out?

It you don't have your partial classes in the GeneratedClasses folder (which I usually don't), wherever you placed your partial classes, they need to have the same namespace as the GeneratedClasses.

So in our example, if we created our Entity Framework classes in the GeneratedClasses folder (ThinController.GeneratedClasses) and we placed our business logic/partial classes in a Classes folder off the root (ThinController.Classes), then your partial class would look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ThinController.Classes
{
    public partial class Faq
    {
    }
}

You need to change the namespace to match your EF generated classes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ThinController.GeneratedClasses
{
    public partial class Faq
    {
    }
}

Now you're on your way.

You can easily add interfaces to your entities. Place an IFaq interface on your partial class and you're all set.

If you need to add an attribute to your class, it's best to create an inherited class and attach the attributes to that particular property or method instead of touching the T4 generated classes.

Conclusion

Even though this walkthrough of Entity Framework was a little slow for some, I hope it gave some developers an idea of how to generate a Data Access Layer relatively quick. If your database was designed correctly, it should take you 70-80% of the way. The only thing left is to attach the business logic to each entity.

ORMs (including Entity Framework) are extremely helpful for building out quick data access layers and getting a prototype up and running relatively fast. If you know how to maximize your ORM tool, you can generate websites and applications with the flick of a switch with little effort.

I hope you've enjoyed this series and if anyone has any other speed techniques, post them in the comments below! I'm always open to new and interesting techniques. :-)

Series: How to take your ASP.NET MVC development to ludicrous speeds.

  1. Transforming XML/JSON/CSV into Classes
  2. Use pre-built applications
  3. T4 (Text Template Transformation Toolkit)
  4. ReSharper/SQL Complete
  5. ORM (Object Relationship Management)

Do you build your applications any differently from any of these 5 methods of coding? Let me know and share with everyone! Post your comment below.

Did you like this content? Show your support by buying me a coffee.

Buy me a coffee  Buy me a coffee
Picture of Jonathan "JD" Danylko

Jonathan Danylko is a web architect and entrepreneur who's been programming for over 25 years. He's developed websites for small, medium, and Fortune 500 companies since 1996.

He currently works at Insight Enterprises as an Principal Software Engineer Architect.

When asked what he likes to do in his spare time, he replies, "I like to write and I like to code. I also like to write about code."

comments powered by Disqus