DEV Community

revoltez
revoltez

Posted on

1 1

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay