Author : MD TAREQ HASSAN
For ASP.Net core app
- Entity Framework contexts are usually added to the service container using the scoped lifetime because web app database operations are normally scoped to the client request
- if a lifetime isn’t specified by an
AddDbContext<TContext>
overload when registering the database context, the default lifetime is scoped - Services of a given lifetime shouldn’t use a database context with a shorter lifetime than the service
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;
}
...
}