DEV Community

revoltez
revoltez

Posted on

how does Entity Framework Core figure out where to get the connection string in .NET Core app?

have you ever wondered how does EF Core finds the connection string even if you have decoupled the connection string from the Context class?

first in Asp.net Core :

what if your context class looks like this

    public class ApplicationDBContext : DbContext
    {
        public ApplicationDBContext(DbContextOptions options):base(options){}

        public DbSet<Employee> Employees { get; set; }   
    }   
Enter fullscreen mode Exit fullscreen mode

the proper way to put the connetion string is to put in a seperate file for example appsettings.json and we usually register the context class in the ConfigureServices
method in startup.cs like this

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDBContext>(
                dbContextOptions =>
                 dbContextOptions.UseMySql(Configuration.GetConnectionString("DefaultConnection"))); 
        }
Enter fullscreen mode Exit fullscreen mode

EF core actually have a convention to follow to find the connection string, if we comment the CreateHostBuilder method EF will output this error

Unable to create an object of type 'ApplicationDBContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Enter fullscreen mode Exit fullscreen mode

this means Entity looks for this method and figure out what is the name of the startup class in the UseStartup method and then figure out how to instantiate the Application context.

in console app

and if you are using a simple console App in .Net Core then and you dont create a constructor with parameters then it simply looks for the OnConfiguiring method and looks for the connection string.

Top comments (0)