Skip to content

Hello, Entity Framework

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.

public class UserService
{
    public IEnumerable<User> GetUsers()
    {
        var ds = new DataSet();

        using (var con = new SqlConnection("Server=myServerAddress;Database=myDataBase;UserId=myUsername;Password=myPassword;"))
        {
            using (var da = new SqlDataAdapter("SELECT * FROM Users", con))
            {
                da.Fill(ds);
            }
        }

        if (ds.Tables.Count == 0)
            return new User[] { };
        return ds.Tables[0].Rows.Cast<DataRow>().Select(x => new User
        {
            Id = (long) x["ID"],
            Username = (string) x["Username"],
            Password = (string) x["Password"]
        });
    }
}

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.

public class UserService
{
    private readonly ApplicationContext _context;

    public UserService(ApplicationContext context)
    {
        _context = context;
    }

    public IEnumerable<User> GetUsers()
    {
        return _context.Users;
    }
}

So which one would you prefer to use?

Are there any alternatives?

Here are a few alternatives that you can check out.

Published in.NETC#

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *