Free Web Development Online Tutorials, Learn to Code
Learn Entity Framework with C#, Entity Framework Core, Code First, DB First Approach

DbContext Class in Entity Framework Core

EF Core DbContext Class in C#

DbContext Class in Entity Framework Core Example, reading connection string from appsettings.json in Asp.net Core DbContext

In this tutorial you will learn how to work with Entity framework Core DbContext Class, How to read connection string from appsettings.json file

This is how the DbContext Class will look like.

Here are few points you need to understand

  • You need a reference of using Microsoft.EntityFrameworkCore class
  • You need a reference of using Microsoft.EntityFrameworkCore class
  • Using static connection string of Startup.cs class
  • Override onConfiguring , setting up extension method for respective data provider, (here UseSqlServer())
  • Creating DbSet property for mapping with database table, property name should be same as table name.
  • Creating DbSet property for mapping with database table, property name should be same as table name.
Custom Class Inherit from DbContext Base Class

Here is how you can design customised DbContext class in your application, the code working sample

using Microsoft.EntityFrameworkCore;
/// <summary>
/// Written by WebTrainingRoom.Com
/// </summary>
namespace AspNetCoreMVC
{
public class EFContext : DbContext
{
public EFContext() : base()
{
}
public static string GetConnectionString()
{
return Startup.DbConnectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var _connectionString = GetConnectionString();
optionsBuilder.UseSqlServer(_connectionString);
}
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasKey(s=>s.StuId);
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Student> tbStudent { get; set; }
    }
}

The above DBContext class code is well tested working code; you can start using in your application


Comment
Name
Email
Website
Subscribe
 
Entity Framework Core DbContext