Entity framework - How to set the connection string of the DbContext

It seems that every guide I find on Entity framework, the database connectionString is fetched from the config file magically. I wanted to inject it instead as a string and I figured out that you can do the following:

namespace MyDbContext
{
    public class MyDbContext : DbContext
    {
        private readonly string _connectionString;

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

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(_connectionString); // if you use MSSQL
        }

        public DbSet<MyEntity> MyEntities { get; set; }
    }

    public class MyEntity {
        public int Id { get; set; }
        public string Text { get; set; }
    }
}

In the above I make the connectionString injectable as a parameter on the constructor. I later use it in the OnConfiguring method when calling UseSqlServer(). That is all there is to it.

For migrations you will likely need a parameterless constructor as well.

I hope you found this helpful, feel free to leave a comment down below!