Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

DbContext Class in Entity Framework Core

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.
Here is 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; }
}
}

Comment
Name Email Website
Subscribe
 
Entity Framework Core DbContext

Group Training