What you need to know about Entity Framework Data Context

This article is a part of a multi-post article on Entity Framework Code First for web applications:

  1. Entity Framework Code First Entities and entity relationships
  2. What do you need to know about Entity Framework Data Context
  3. Entity Framework Migrations and Data seeding

This article is the second part of the posts. The first part talks about defining entities and relationships. You may find the first article in this link. Let’s continue by talking about the data context in the Data Access Layer.

Entity Framework enables us to abstract the data layer and communicate with the database for the Create, Read, Update, and Delete (CRUD) operations. We also defined the relationship between entity classes and database tables. Just as every table is enclosed inside a database, in Entity Framework, entities are enclosed inside a data context to abstract a database. The primary class that creates this context is the DbContext class of System.Data.Entity namespace. To abstract a database, we usually create a class representing our context which extends DbContext class. Let us suppose that we have a database called HumanResources and we want to connect to that database using Entity Framework. Our Entity Framework Data Context would look like this at beginning:

The DbContext class that we extend will allow us to define our database tables as sets of entities (DbSet<T>), and then, we can query the database and do all the CRUD operations using those sets. Entity Framework will convert all those actions we perform to SQL queries, execute them towards the database, and return us the results back. DbContext even offers these operations in synchronous and asynchronous modes.

From the previous post, we had defined two entities, Person and Country. Let’s define them inside our context.

We pluralize the names of the sets as they represent the table of persons/countries, so multiple records are represented.

The DbContext’s lifetime starts with the instantiation of the object and it will end when the object is disposed or garbage collected. If we want to manage the lifetime of the context, we can put it inside a using construct to dispose it when we are done. During the lifetime, it will also manage opening and closing of connections to the database. E.g.

In the example below, we have created an instance of the HumanResourcesContext. Inside the curly braces, we have queried the persons table to find the person with the id equal to 1 (db.Persons.find(1)). DbContext allows us to query the database using the name of the DbSet properties we have define (which point to database tables), but the actual query is not executed when we say like db.Persons. The queries are executed when we ask the context for concrete data, like in our example with finding the person with id equal to 1. Other forms that we ask the context for the data could be execution of ToList(), ToArray(), Single() methods.

When using with ASP.NET, we should create a context per request. If we do it, we should use using during the process of request, or if we do it using an Inversion of Control (IoC) container, we should define the initialization of our context class as per request.

There is one more important thing to note here. We queried the database without even specifying the connection string for the Entity Framework. How does it know where to connect? By default, it uses the default connection string in asp.net (found in web.config in versions prior ASP.NET 5) and make the connection using it. If you want to specify a specific connection string, e.g. if we have a connection string named myConnectionString defined in web.config, you may pass it to the constructor of DbContext like this:

or hardcode it if you want (I would not recommend it)

Summary

DbContext class allows us to create the data context of our database abstraction. It allows us to perform CRUD operations towards our database using code first approach without writing SQL queries.

 

Train yourself on ASP.NET web development

I have always been supporter of the formal education as a primary way of one’s intellectual forming. However, there are times you need a quick push on a topic you have no experience, or formal education. If this is your case, then here is my advice.

You need to have a curriculum to support your knowledge development, instead of trying to grasp the topic from blog posts and internet pages. As humans tend to learn visually faster than by reading, starting with video training would be a better choice.

Pluralsight is a video training provider for developer topics with videos prepared by some of the most known authors and industry experts of software development community. From the range of the courses offered, here is a learning path I would suggest, from the range of training provided from Pluralsight.

Lets start progressively, from basics to more advanced topics, so here are the courses in this order:

  1. HTML Fundamentals
  2. HTML5 Fundamentals
  3. Using HTML5 and CSS3
  4. JavaScript Fundamentals
  5. Structuring JavaScript Code
  6. jQuery Fundamentals
  7. A Web developer’s guide to images
  8. ASP.NET MVC4 Fundamentals
  9. Building Applications with ASP.NET MVC 4
  10. Building ASP.NET MVC Apps with EF Code First, HTML5, and jQuery
  11. Web performance
  12. Scrum Fundamentals

This curricula is prepared in a way so you will progressively develop yourself to be a web developer. First, you will start with HTML, then continue with HTML5, the hot topic of our time, and proceed further with mixing HTML5 and CSS3 to create modern sites. After that, the curricula continues with JavaScript, the ultimate language of browsers, to continue with a guide to images,  and then further advance with server side programming using ASP.NET MVC framework. At the end, course finishes with Web performance topic to create optimal fast loading sites, and Scrum fundamentals, to develop a structured software development process. 

If you follow this path, my suggestion is that you allow yourself at least two months, if not more, to go through these courses.

I would like to hear your opinion, especially about the results if you have followed this learning path.