entityframework core using sql server database

Introduction :

In this tutorial we will discuss entityframework core using sql server database. When we are using Entity Framework Core, one of the important things that we need to configure database provider that we plan to use. Entity Framework Core supports a wide variety of databases including non-relational databases. Here we want to configure and use Microsoft SQL Server with entity framework core.

  • We want to configure and use Microsoft SQL Server with entity framework core.
  • so we are usually specify this configuration in ConfigureServices() method in Startup.cs file.

Startup.cs :

    public class Startup
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
            Configuration = configuration;

        public void ConfigureServices(IServiceCollection services)
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MySqlCon")));


  • We can use either AddDbContext() or AddDbContextPool() method to register our application specific DbContext class.
  • The difference between AddDbContextPool() and AddDbContext() methods is, AddDbContextPool() method provides DbContext pooling.
  • With DbContext pooling, an instance from the DbContext pool is provided if available, rather than creating a new instance.
  • DbContext pooling is conceptually similar to how connection pooling works in ADO.NET.
    From a performance standpoint AddDbContextPool() method is better over AddDbContext() method.

ASP.NET Core Database Connection String in entityframework core

Here we are storing ConnectionString in appsettings.json file instead of hard coded connectionstring so its easy to change database connection.

  "ConnectionStrings": {

To read connection string from appsettings.json file we use IConfiguration service GetConnectionString() method.

UseSqlServer() Method

  • UseSqlServer() method is used to configure our application specific DbContext class to use SQL Server as the database.
    public class AppDbContext : DbContext
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)

  • To connect to a database, we need the database connection string which is provided as a parameter to UseSqlServer() extension method

Leave a Reply

Your email address will not be published.