Entity Framework - DbContext



The Entity Framework enables you to query, insert, update, and delete data, using Common Language Runtime (CLR) objects which is known as entities. The Entity Framework maps the entities and relationships that are defined in your model to a database. It also provides facilities to −

  • Materialize data returned from the database as entity objects
  • Track changes that were made to the objects
  • Handle concurrency
  • Propagate object changes back to the database
  • Bind objects to controls

The primary class that is responsible for interacting with data as objects is System.Data.Entity.DbContext. The DbContext API is not released as part of the .NET Framework. In order to be more flexible and frequent with releasing new features to Code First and the DbContext API, the Entity Framework team distributes EntityFramework.dll through Microsoft’s NuGet distribution feature.

  • NuGet allows you to add references to your .NET projects by pulling the relevant DLLs directly into your project from the Web.

  • A Visual Studio extension called the Library Package Manager provides an easy way to pull the appropriate assembly from the Web into your projects.

DbContext
  • DbContext API is mostly targeted at simplifying your interaction with Entity Framework.

  • It also reduces the number of methods and properties you need to access commonly used tasks.

  • In previous versions of Entity Framework, these tasks were often complicated to discover and code.

  • The context class manages the entity objects during run time, which includes populating objects with data from a database, change tracking, and persisting data to the database.

Defining a DbContext Derived Class

The recommended way to work with context is to define a class that derives from DbContext and exposes DbSet properties that represent collections of the specified entities in the context. If you are working with the EF Designer, the context will be generated for you. If you are working with Code First, you will typically write the context yourself.

The following code is a simple example which shows that UniContext is derived from DbContext.

  • You can use automatic properties with DbSet such as getter and setter.

  • It also makes much cleaner code, but you aren’t required to use it for the purpose of creating a DbSet when you have no other logic to apply.

public class UniContext : DbContext {
   public UniContext() : base("UniContext") { }
   public DbSet<Student> Students { get; set; }
   public DbSet<Enrollment> Enrollments { get; set; }
   public DbSet<Course> Courses { get; set; }
}
  • Previously, EDM used to generate context classes that were derived from the ObjectContext class.

  • Working with ObjectContext was a little complex.

  • DbContext is a wrapper around ObjectContext which is actually similar to ObjectContext and is useful and easy in all the development models such Code First, Model First and Database First.

Queries

There are three types of queries you can use such as −

  • Adding a new entity.
  • Changing or updating the property values of an existing entity.
  • Deleting an existing entity.

Adding New Entities

Adding a new object with Entity Framework is as simple as constructing a new instance of your object and registering it using the Add method on DbSet. The following code is for when you want to add a new student to database.

private static void AddStudent() {

   using (var context = new UniContext()) {

      var student = new Student {
         LastName = "Khan", 
         FirstMidName = "Ali", 
         EnrollmentDate = DateTime.Parse("2005-09-01") 
      };

      context.Students.Add(student); 
      context.SaveChanges();

   }
}

Changing Existing Entities

Changing existing objects is as simple as updating the value assigned to the property(s) you want changed and calling SaveChanges. In the following code, the last name of Ali has been changed from Khan to Aslam.

private static void AddStudent() {

   private static void ChangeStudent() {

      using (var context = new UniContext()) {

         var student = (from d in context.Students
            where d.FirstMidName == "Ali" select d).Single();
         student.LastName = "Aslam";
         context.SaveChanges();

      }
   }
}

Deleting Existing Entities

To delete an entity using Entity Framework, you use the Remove method on DbSet. Remove works for both existing and newly added entities. Calling Remove on an entity that has been added but not yet saved to the database will cancel the addition of the entity. The entity is removed from the change tracker and is no longer tracked by the DbContext. Calling Remove on an existing entity that is being change-tracked will register the entity for deletion the next time SaveChanges is called. The following example shows an instance where the student is removed from the database whose first name is Ali.

private static void DeleteStudent() {

   using (var context = new UniContext()) {
      var bay = (from d in context.Students where d.FirstMidName == "Ali" select d).Single();
      context.Students.Remove(bay);
      context.SaveChanges();
   }
}
Advertisements