Free Web Development Online Tutorials, Learn to Code
How to use DbContext Class in Entity Framework Core, dbcontext c# .net core

DbContext Class in Entity Framework Core

Learn how to design DbContext class in Entity Framework Core C#.

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

This is how you can design customised DbContext class in your application, Look at the beloe "EFContext : DbContext" class, this is working code 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

Now you can write any database related operation using above EFContext class, here is an example of adding student to database using dbcontext class.

public Student AddStudent(Student s)
{
    using (EFContext context = new EFContext())
    {
        context.tbStudent.Add(s);
        context.SaveChanges();
    }
    return s;
}

Probably you should look at how all CRUD operations are written using DbContext

Comment
Name
Email
Website
Subscribe
 
learn entity framework
Entity Framework Core DbContext

Entity Framework Interview Questions

Entity Framework C# Examples | Join .Net C# Course