简体   繁体   中英

How should I store the entity framework 6 connection string when using .net core

I've got a .net core REST api project that calls a .net 4.6 assembly that uses entity framework. I also have a test project calling that assembly. The old way for giving the connection string was to have the connection string in the App or web.Config looking like

<connectionStrings>
    <add name="MyDbContext" connectionString="data source=(LocalDB)\MSSQLLocalDB;AttachDBFilename=|DataDirectory|\TestDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>

and your dbContext did

public MyDbContext(): base("name=MyDbContext")

I assume I have to put the info in my appsettings.Json like

"ConnectionStrings": {
  "MyDatabase": "Server=(localdb)\\mssqllocaldb;Database=TestDB;Trusted_Connection=True;"
},

but then I need to change my DbContext how? and how does my test project set the connection string?

This should be an easy one that loads of people have done before but I couldn't find any examples in my googling. Thanks.

well that didn't get much interest. I've got a working solution but I'm not convinced I've gone about it right, anyone got anything better?

I've created a new Settings class to hold settings, currently just the DbConnection

public class Settings
{
    public string DBConnection { get; set; }
}

Then I put the settings in the appsettings.json

"Settings": {
    "DBConnection": "Server=(localdb)\\mssqllocaldb;Database=TestDB;Trusted_Connection=True;"  
}

And bind this configuration to the Settings object in Startup

private void AddConfigurationSettingsSingleton(IServiceCollection services)
{
    var config = new Settings();
    Configuration.GetSection("Settings").Bind(config);
    services.AddSingleton(config);
}

Then the DI sticks it in anywhere it's required.

public class Repository
{
    private readonly SkinDbContext dbContext; 
    public Repository(Settings settings)
    {
        dbContext = new MyDbContext(settings.DBConnection);
    }

Any my DBContext takes the connection string

public class MyDbContext: DbContext
{
    public MyDbContext(string connectionString): base(connectionString)
    {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM