Author : HASSAN MD TAREQ

ASP .Net Core App

  • Data layer => EF Core data project (i.e. AdventureWorks.Data, AdventureWorks is the sample database provided by Microsoft)
  • .AddDbContextPool<TDbContext>(<lambda>) => lambda will be called with DbContextOptions<TDbContext>
  • DbContextOptions<TDbContext> is used to set connection string
  • See more (advanced): using-dbcontext-with-dependency-injection in ASP.Net core app

appsettings.json

{

  "ConnectionStrings": {
    "DefaultDatabase": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=FooDB;Integrated Security=True"
  }
}
public class Startup
{
	public IConfiguration Configuration { get; }

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


	public void ConfigureServices(IServiceCollection services)
	{
		var dbConnectionString = Configuration.GetConnectionString("DefaultDatabase");
		services.AddDbContextPool<MasterMaintenanceContext>(options => options.UseSqlServer(dbConnectionString));

		// ... ... ...
	}
}

We need to modify the DbContext class so that connection string can be configured in Startup.ConfigureServices(...) of ASP.Net core project

EmployeeDbContext.cs

public class EmployeeDbContext : DbContext
{

	public EmployeeDbContext(DbContextOptions<EmployeeDbContext> options) : base(options) 
	{
		// connection string is already set by configuring options in `Startup.ConfigureServices(...)`
	}

	public DbSet<Employee> Employees { get; set; }
}

Console App

Code and Commands (screenshoots below)

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.Extensions.Configuration.Json

appsettings.json

{
  "connectionStrings": {
    "AdventureWorks": "Data Source=DESKTOP-OJLNQ8G\\SQLSERVERDEV;Initial Catalog=AdventureWorks2017;Integrated Security=True"
  }
}

DbContext constructor

	private readonly string _connectionString;

	public AdventureworksDbContext(string connectionString)
	{
		_connectionString = connectionString;
	}

	protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
	{
		if (!optionsBuilder.IsConfigured)
		{
			optionsBuilder.UseSqlServer(_connectionString);
		}
	}

Console app: Program.cs

using System;
using System.Diagnostics;
using System.Linq;
using System.IO;
using AdventureWorks.Data;
using Microsoft.Extensions.Configuration;

namespace AdventureWorks.ConsoleApp
{
    class Program
    {
        private static IConfiguration _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", true, true)
            .Build();

        private static readonly string _connectionString = _configuration.GetConnectionString("AdventureWorks");

        static void Main(string[] args)
        {

            var awDbContext = new AdventureworksDbContext(_connectionString);

            foreach (var person in awDbContext.People.Take(10))
            {
                Debug.WriteLine($"{person.FirstName}");
            }
        }
    }
}

Step-1

Using EF Core data layer in a console app Step 1

Step-2

Using EF Core data layer in a console app Step 2

Step-3

Using EF Core data layer in a console app Step 3

Step-4

Using EF Core data layer in a console app Step 4

Step-5

Using EF Core data layer in a console app Step 5

Step-6

Using EF Core data layer in a console app Step 6

Step-7

Using EF Core data layer in a console app Step 7

Step-8

Using EF Core data layer in a console app Step 8

Step-9

Using EF Core data layer in a console app Step 9

Step-10

Using EF Core data layer in a console app Step 10

Step-11

Using EF Core data layer in a console app Step 11

Step-12

Using EF Core data layer in a console app Step 12

Step-13

Using EF Core data layer in a console app Step 13

Without DI injection

Courtesy: https://www.koskila.net/how-to-instantiate-your-dbcontext-outside-your-data-project/

using Microsoft.EntityFrameworkCore;
using System;
 
namespace YourNamespace
{
    public class YourClass
    {
        private string _connectionString = "This comes from your configuration file";
 
        public YourClass()
        {
           // In this example, "ApplicationDbContext" is my DbContext class
           var options = new DbContextOptionsBuilder<ApplicationDbContext>()
                   .UseSqlServer(_connectionString)
                   .Options;
 
            // With the options generated above, we can then just construct a new DbContext class
            using (var ctx = new ApplicationDbContext(options))
            {
               // Your code here
            }
         }
    }
}