Click here to Skip to main content
15,888,527 members
Articles / Entity Framework / Entity Framework 6.0

What you need to know about Entity Framework Data Context

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
25 Sep 2015CPOL3 min read 8.7K   3  
This article is a part of a multi-post article on Entity Framework Code First for web applications: Entity Framework Code First Entities and entity relationships What do you need to know about Entity Framework Data Context Entity Framework Migrations and Data seeding This article is the second

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:

public class HumanResourcesContext : DbContext
{
}

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.

public class HumanResourcesContext : DbContext
{
  DbSet<Person> Persons;
  DbSet<Country> Countries;
}

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.

using (var db = new HumanResourcesContext)
{
   Person testPerson = db.Persons.find(1);
}

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:

public class HumanResourcesContext : DbContext
{
 public HumanResourcesContext() : base("myConnectionString")
 {
 }
}

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

public class HumanResourcesContext : DbContext
{
   public HumanResourcesContext() : base("Data Source=(LocalDb)\...")
   {
   }
}

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.

The post What you need to know about Entity Framework Data Context appeared first on arian-celina.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Albania Albania
I am a Software Architect, a web developer, and a Computer Science lecturer. I enjoy solving business problems by providing software solutions to them. My favorite technologies and fields of interest include ASP.NET, C# programming language, Java programming language, Javascript, jQuery, AngularJS, Web Services, REST, and mobile application development

Comments and Discussions

 
-- There are no messages in this forum --