Hello, Entity Framework

Hello, Entity Framework
Photo by Tobias Fischer on Unsplash

With the near release of Entity Framework 7, I thought it was about time I gave my two cents on the usefulness of the current version. I’ve been using it for a few years now, and have found it easy (and fun) to use.

But, what is Entity Framework?

Entity Framework is an open source object-relational mapping (or ORM for short) framework for ADO.NET. This means you can create models in your code that map to tables in your database. It can plug in to an existing database and can automatically generate models for you (although this is not possible when using Code First).

It’s nice level of abstraction means you can hook up all sorts of databases to it. For example, you could have a connection defining a connection to a LocalDB instance, and another for connection to an MySQL database.

Why should I use Entity Framework?

Sure, you could use the standard DbConnection classes meaning you have to:

  • Manually create connections to a database.
  • Manually create SQL commands to perform queries or actions on your database.

Here is an example UserService to demonstrate the above.

But what if you want to change what type of database you are using?

  • You would have to manually modify all your connection strings.
  • You would have to manually modify all your queries to make sure they work with the new connection.

Entity Framework to the rescue!

With Entity Framework you only need to:

  • Add the new database dependencies (easily done via NuGet)
  • Modify the connection string in your app/web.config

Here is how the UserService will look using Entity Framework.

So which one would you prefer to use?

Are there any alternatives?

Here are a few alternatives that you can check out.