Tutorials Menu

DbContext in Entity framework with Example

What is an Entity in EF?

An Entity is a Plain Old CLR Object (POCO) class that represents a database table. The properties within this class correspond to the columns of the table it models, with their names directly mapping to the column names. For the “code-first" approach we write the entity classes ourselves and for the “database-first” approach we use tools to generate the entities from an already existing database.

Example of an Entity object

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Address { get; set; }
}

What is DbContext in EF?

The DbContext is an object responsible for establishing a connection with your database, enabling you to execute queries and save your entity objects. Additionally, the DbContext provides access to most Entity Framework features, including:

  • Database Connection: Configures and establishes the connection to the database.
  • Entity Declaration: Declare entity models and define relationships between them.
  • Change Tracking: Automatically keeps track of modifications made to your entities.
  • Convention Settings: Manages default configurations and conventions for entity mappings.
  • Data Manipulation: Handles operations like inserts, updates, deletes, and reads.
  • Database Migrations: Facilitates schema updates and versioning of your database.

First thing you need to do is create your own implementation of the DbContext class

public class SupermarketContext : DbContext
{
}

How to set up the database connection?

Entity framework uses connection string to specify the database it connects to. To set up a connection string you first need to override the OnConfiguring method. The OnConfiguring method accepts one argument of type DbContextOptionsBuilder. This optionsBuilder object offers various extension methods for selecting different server types. The connection string is passed as a parameter to the chosen extension method.

public class SupermarketContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=localhost\SQLEXPRESS;Initial Catalog=SuperMarket_Dev;Integrated Security=True;TrustServerCertificate=True;");

        base.OnConfiguring(optionsBuilder);
    }
}

Note: It is recommended to pull your connection string from a configuration file or environment variable.

How to add an Entity to the context?

Adding an Entity to the context is straightforward. It could be achieved in two ways.

  1. Entry exposed by the DbContext

    Create a public property of type DbSet<Entity> Entities.

    public class SupermarketContext : DbContext
    {
        public DbSet<Store> Stores { get; set; }
    }
    
  2. Entry not exposed by the DbContext

    If you don't want the DbContext to expose your Entity as a DbSet property you can register it using the modelBuilder.Entity method inside the OnModelCreating override.

  3. protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>();
    }