Author : MD TAREQ HASSAN

For ASP.Net core app

Code first approach: create entity classes and create DbContext using entity classes
Database first approach: DbContext and entity classes will be in EF core data project

For database first approach, we need to add a constructor that accepts DbContextOptions<TDbContext>

UsersDbContext.cs

public class UsersDbContext : DbContext
{
    public UsersDbContext(DbContextOptions<UsersDbContext> options) : base(options)
    {
    }
    
    public DbSet<UserModel> Users { get; set; }
}

Register in Startup

Preferred way: AddDbContextPool

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool<UsersDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("UserDBConnection")));

    services.AddMvc();
}

Normal way: AddDbContext

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<UsersDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("UserDBConnection")));

    services.AddMvc();
}

See: AddDbContext vs AddDbContextPool

If the app uses Authentication

public void ConfigureServices(IServiceCollection services)
{

    // for Authentication and Authorization
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("AuthDBConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
        
    // for using EF core data project in app
    services.AddDbContext<UsersDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("UserDBConnection")));

    services.AddMvc();
}

Constructor injection

FooService.cs

public class MyController
{
    private readonly BloggingContext _context;

    public MyController(BloggingContext context)
    {
      _context = context;
    }

    ...
}