EntityFramework.Docs icon indicating copy to clipboard operation
EntityFramework.Docs copied to clipboard

Show more examples of obtaining and setting connection strings

Open bdaniel7 opened this issue 7 years ago • 3 comments

What if I need to use a connection string from the config file? like, you know,

public ApplicationDbContext CreateDbContext(string[] args)
{
	var builder = new DbContextOptionsBuilder<ApplicationDbContext>();

	builder.UseSqlServer( --> Configuration.GetConnectionString("DefaultConnection") <-- );

	return new ApplicationDbContext(builder.Options);
}

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

bdaniel7 avatar Oct 30 '18 15:10 bdaniel7

Hey @bdaniel7!

You could add the code for acquiring a connection string inside the CreateDbContext method. Have a look into issue https://github.com/aspnet/EntityFrameworkCore/issues/8332 where others were facing the same problem and provided their solution.

Cheers, René

Advanium avatar Nov 08 '18 20:11 Advanium

Helpful, but why not update the docs HERE with a real world example.

bproven avatar Jun 15 '19 00:06 bproven

I use json.net and File.ReadAllText to load config in appsettings.json

public EFContext CreateDbContext(string[] args)
        {
            var text = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "appsettings.json"));
            var config = JsonConvert.DeserializeObject(text) as JObject;
            var connectionString = config["ConnectionStrings"]["SqliteConn"].ToString();
            var optionsBuilder = new DbContextOptionsBuilder<EFContext>();
            optionsBuilder.UseSqlite(connectionString);
            return new EFContext (optionsBuilder.Options);
        }

DHclly avatar Aug 30 '19 09:08 DHclly