EntityFramework.Docs
EntityFramework.Docs copied to clipboard
Show more examples of obtaining and setting connection strings
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.
- ID: 2fa64390-1232-8dd3-f170-7d5c68e29ad9
- Version Independent ID: 245bbba8-3102-4a66-15eb-650e05eb9e62
- Content: Design-time DbContext Creation - EF Core
- Content Source: entity-framework/core/miscellaneous/cli/dbcontext-creation.md
- Product: entity-framework
- GitHub Login: @bricelam
- Microsoft Alias: bricelam
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é
Helpful, but why not update the docs HERE with a real world example.
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);
}