How can I implement DbContext Connection String in .NET Core?












18















My situation is quite similar to this link or at least my code is similar and I am trying to find a way to apply this same method in .NET Core syntax.



Pass connection string to code-first DbContext



My specific code is as follows:



public partial class CompanyFormsContext : DbContext
{
public CompanyFormsContext()
: base("name=CompanyFormsContext")
{
}

public CompanyFormsContext(string connName)
: base("name=" + connName)
{
}
...
}


I get an error saying:




Error CS1503 Argument 1: cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions' CompanyForms..NETCoreApp,Version=v1.0




when I go over the parenthesis in base("name=CompanyFormsContext") or base("name=" = connName).



What is the correct way of implementing this functionality in .NET Core?



Edit:



I wanted to share that I have the following information for database connection in my appsettings.json file: (However, I do not have settings in the startup.cs)



  "Data": {
"CompanyFormsContext": {
"ConnectionString": "Server=(localdb)\projectsv13;Database=companyforms;Trusted_Connection=True;"
},
"CompanyFormsContextQA": {
"ConnectionString": "Server=(localdb)\projectsv13;Database=companyforms;Trusted_Connection=True;"
}
}


and I have found the following link Adding DbContextOptions in Startup.cs not registering data store in the website and I am wondering if a simple protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) will be enough to fix my connection or not?



From the link:



services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<MyDbContext>(
options =>
options.UseSqlServer(Configuration.Get("Data:CompanyFormsContext:ConnectionString"))
);


Do I need this kind of a service in my Startup.cs?










share|improve this question

























  • That link was really useful for learning different kinds of Db connections, I am now much more aware of what the problem is. Thank you.

    – Kemal Tezer Dilsiz
    Aug 10 '16 at 17:53











  • Sorry missed your edit. Definately on the right track, see if my answer helps.

    – Peter
    Aug 10 '16 at 18:18
















18















My situation is quite similar to this link or at least my code is similar and I am trying to find a way to apply this same method in .NET Core syntax.



Pass connection string to code-first DbContext



My specific code is as follows:



public partial class CompanyFormsContext : DbContext
{
public CompanyFormsContext()
: base("name=CompanyFormsContext")
{
}

public CompanyFormsContext(string connName)
: base("name=" + connName)
{
}
...
}


I get an error saying:




Error CS1503 Argument 1: cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions' CompanyForms..NETCoreApp,Version=v1.0




when I go over the parenthesis in base("name=CompanyFormsContext") or base("name=" = connName).



What is the correct way of implementing this functionality in .NET Core?



Edit:



I wanted to share that I have the following information for database connection in my appsettings.json file: (However, I do not have settings in the startup.cs)



  "Data": {
"CompanyFormsContext": {
"ConnectionString": "Server=(localdb)\projectsv13;Database=companyforms;Trusted_Connection=True;"
},
"CompanyFormsContextQA": {
"ConnectionString": "Server=(localdb)\projectsv13;Database=companyforms;Trusted_Connection=True;"
}
}


and I have found the following link Adding DbContextOptions in Startup.cs not registering data store in the website and I am wondering if a simple protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) will be enough to fix my connection or not?



From the link:



services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<MyDbContext>(
options =>
options.UseSqlServer(Configuration.Get("Data:CompanyFormsContext:ConnectionString"))
);


Do I need this kind of a service in my Startup.cs?










share|improve this question

























  • That link was really useful for learning different kinds of Db connections, I am now much more aware of what the problem is. Thank you.

    – Kemal Tezer Dilsiz
    Aug 10 '16 at 17:53











  • Sorry missed your edit. Definately on the right track, see if my answer helps.

    – Peter
    Aug 10 '16 at 18:18














18












18








18


3






My situation is quite similar to this link or at least my code is similar and I am trying to find a way to apply this same method in .NET Core syntax.



Pass connection string to code-first DbContext



My specific code is as follows:



public partial class CompanyFormsContext : DbContext
{
public CompanyFormsContext()
: base("name=CompanyFormsContext")
{
}

public CompanyFormsContext(string connName)
: base("name=" + connName)
{
}
...
}


I get an error saying:




Error CS1503 Argument 1: cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions' CompanyForms..NETCoreApp,Version=v1.0




when I go over the parenthesis in base("name=CompanyFormsContext") or base("name=" = connName).



What is the correct way of implementing this functionality in .NET Core?



Edit:



I wanted to share that I have the following information for database connection in my appsettings.json file: (However, I do not have settings in the startup.cs)



  "Data": {
"CompanyFormsContext": {
"ConnectionString": "Server=(localdb)\projectsv13;Database=companyforms;Trusted_Connection=True;"
},
"CompanyFormsContextQA": {
"ConnectionString": "Server=(localdb)\projectsv13;Database=companyforms;Trusted_Connection=True;"
}
}


and I have found the following link Adding DbContextOptions in Startup.cs not registering data store in the website and I am wondering if a simple protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) will be enough to fix my connection or not?



From the link:



services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<MyDbContext>(
options =>
options.UseSqlServer(Configuration.Get("Data:CompanyFormsContext:ConnectionString"))
);


Do I need this kind of a service in my Startup.cs?










share|improve this question
















My situation is quite similar to this link or at least my code is similar and I am trying to find a way to apply this same method in .NET Core syntax.



Pass connection string to code-first DbContext



My specific code is as follows:



public partial class CompanyFormsContext : DbContext
{
public CompanyFormsContext()
: base("name=CompanyFormsContext")
{
}

public CompanyFormsContext(string connName)
: base("name=" + connName)
{
}
...
}


I get an error saying:




Error CS1503 Argument 1: cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions' CompanyForms..NETCoreApp,Version=v1.0




when I go over the parenthesis in base("name=CompanyFormsContext") or base("name=" = connName).



What is the correct way of implementing this functionality in .NET Core?



Edit:



I wanted to share that I have the following information for database connection in my appsettings.json file: (However, I do not have settings in the startup.cs)



  "Data": {
"CompanyFormsContext": {
"ConnectionString": "Server=(localdb)\projectsv13;Database=companyforms;Trusted_Connection=True;"
},
"CompanyFormsContextQA": {
"ConnectionString": "Server=(localdb)\projectsv13;Database=companyforms;Trusted_Connection=True;"
}
}


and I have found the following link Adding DbContextOptions in Startup.cs not registering data store in the website and I am wondering if a simple protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) will be enough to fix my connection or not?



From the link:



services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<MyDbContext>(
options =>
options.UseSqlServer(Configuration.Get("Data:CompanyFormsContext:ConnectionString"))
);


Do I need this kind of a service in my Startup.cs?







c# asp.net .net entity-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 23 '17 at 12:10









Community

11




11










asked Aug 10 '16 at 15:48









Kemal Tezer DilsizKemal Tezer Dilsiz

89431027




89431027













  • That link was really useful for learning different kinds of Db connections, I am now much more aware of what the problem is. Thank you.

    – Kemal Tezer Dilsiz
    Aug 10 '16 at 17:53











  • Sorry missed your edit. Definately on the right track, see if my answer helps.

    – Peter
    Aug 10 '16 at 18:18



















  • That link was really useful for learning different kinds of Db connections, I am now much more aware of what the problem is. Thank you.

    – Kemal Tezer Dilsiz
    Aug 10 '16 at 17:53











  • Sorry missed your edit. Definately on the right track, see if my answer helps.

    – Peter
    Aug 10 '16 at 18:18

















That link was really useful for learning different kinds of Db connections, I am now much more aware of what the problem is. Thank you.

– Kemal Tezer Dilsiz
Aug 10 '16 at 17:53





That link was really useful for learning different kinds of Db connections, I am now much more aware of what the problem is. Thank you.

– Kemal Tezer Dilsiz
Aug 10 '16 at 17:53













Sorry missed your edit. Definately on the right track, see if my answer helps.

– Peter
Aug 10 '16 at 18:18





Sorry missed your edit. Definately on the right track, see if my answer helps.

– Peter
Aug 10 '16 at 18:18












4 Answers
4






active

oldest

votes


















17














Another option would be to call the base constructor that takes a DbContextOptions:



public BooksContext(string connectionString) : base(GetOptions(connectionString))
{
}

private static DbContextOptions GetOptions(string connectionString)
{
return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}





share|improve this answer





















  • 1





    had to change this to base but great solution!

    – aherrick
    Oct 18 '18 at 12:56











  • And how can i use this for oracle database ?, there is no UseOracle or somthing like that..

    – Terai
    Jan 7 at 12:56






  • 1





    Microsoft does not provide one for Oracle, you need to use a third-party. Depending on it, the extension method may be different. Please see docs.microsoft.com/en-us/ef/core/providers.

    – Ricardo Peres
    Jan 7 at 13:12



















13














Generally you are going to want to read it from config at start-up, and then use the connection string to configure an Entity Framework DbContext service for your process.



1) Add a line to your appsettings.json:



"DbConnectionString": "Server=s;Database=db;Trusted_Connection=True;",


2) Read the line in you Startup.cs class (after the Startup method is called to build the Configuration - so usually in the ConfigureServices method) like this:



var connection = Configuration["DbConnectionString"];


3) If using Entity Framework add a database context service (MyDbContext is the context class generated by EF). You also want to tell the built-in dependency injection how to instantiate your database context:



services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));
services.AddScoped<IMyDbContext, MyDbContext>();


Where IMyDbContext is (at it's simplist) just an interface you've extracted from your MyDbContext



4) Now you can define your controller to take a MyDbContext and the DI will take care of building it and passing it in when the controller is invoked:



public MyController(IMyDbContext context)
{
_context = context // store for later use
}





share|improve this answer

































    4














    IMO best practice:



    add to your configuration.json:



         "ConnectionStrings": {
    "BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
    }


    and to initialize section:



    services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));





    share|improve this answer































      -1














      So I searched all over for a solution to my issue which was I needed to dynamically connect to a database based on data that I do not have until time to do the connecting. Basically, dynamic context. I did not have the data being passed on the URL, and I did not have a short list of possible databases to attach to). So, here is my solution to the issue posed. This code will allow you to use the appsettings.json file to define the connection string with a placeholder to be replaced at run time by the code. This can be done within a controller or some other class as you see fit.



      I am using both a static context and a dynamic context but you could use dynamic only.



      Hopefully someone will stumble upon this and say thank god...although probably just as likely someone will say, this guy is an idiot. Either way, enjoy.



      using System;
      using System.Globalization;
      using System.Linq;
      using Microsoft.Extensions.Configuration;

      namespace CallCenter.Repositories
      {
      public class TestRepository : ITestRepository
      {
      private readonly InsuranceContext _context;
      public TestRepository InsuranceContext context)
      {
      _context = context;
      }

      public void Add(string passedInStringWhichTellsWhatDatabaseToUse)
      {
      var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");

      var configuration = builder.Build();
      var connectionString = configuration.GetConnectionString("DefaultConnection");


      var agencyContext = new AgencyContext(connectionString.Replace("Database=replacethisstring", "Database=" + passedInStringWhichTellsWhatDatabaseToUse));

      var company = agencyContext.Companys.FirstOrDefault(x => x.ColumnNameInDb == "xyz");
      if (company != null)
      {
      companyId = company.CompanyId.ToString();
      }

      ... your other code here which could include the using the passed in _context from the injected code (or you could not have any context passed in and just use dynamic context
      }

      }
      }
      }

      //The AgencyContext class would look like this:

      using Microsoft.EntityFrameworkCore;

      namespace CallCenter.Entities
      {
      public class AgencyContext : DbContext
      {
      public AgencyContext(string connectionString) : base(GetOptions(connectionString))
      {

      }

      private static DbContextOptions GetOptions(string connectionString)
      {
      return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
      }

      public DbSet<Companys> Companys { get; set; }
      }
      }

      //The startup.c IServiceProvider module has this:

      public IServiceProvider ConfigureServices(IServiceCollection services)
      {
      services.AddOptions();

      services.AddDbContext<InsuranceContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.UseRowNumberForPaging()));
      services.AddScoped<ITestRepository , TestRepository >();
      ....
      }


      And finally the appsettings.jason file would have this in it:



      {
      "ConnectionStrings": {
      "DefaultConnection": "Server=yourservername;Database=replacethisstring;User ID=youruserid;Password=yourpassword;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
      }
      }





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38878140%2fhow-can-i-implement-dbcontext-connection-string-in-net-core%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        17














        Another option would be to call the base constructor that takes a DbContextOptions:



        public BooksContext(string connectionString) : base(GetOptions(connectionString))
        {
        }

        private static DbContextOptions GetOptions(string connectionString)
        {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
        }





        share|improve this answer





















        • 1





          had to change this to base but great solution!

          – aherrick
          Oct 18 '18 at 12:56











        • And how can i use this for oracle database ?, there is no UseOracle or somthing like that..

          – Terai
          Jan 7 at 12:56






        • 1





          Microsoft does not provide one for Oracle, you need to use a third-party. Depending on it, the extension method may be different. Please see docs.microsoft.com/en-us/ef/core/providers.

          – Ricardo Peres
          Jan 7 at 13:12
















        17














        Another option would be to call the base constructor that takes a DbContextOptions:



        public BooksContext(string connectionString) : base(GetOptions(connectionString))
        {
        }

        private static DbContextOptions GetOptions(string connectionString)
        {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
        }





        share|improve this answer





















        • 1





          had to change this to base but great solution!

          – aherrick
          Oct 18 '18 at 12:56











        • And how can i use this for oracle database ?, there is no UseOracle or somthing like that..

          – Terai
          Jan 7 at 12:56






        • 1





          Microsoft does not provide one for Oracle, you need to use a third-party. Depending on it, the extension method may be different. Please see docs.microsoft.com/en-us/ef/core/providers.

          – Ricardo Peres
          Jan 7 at 13:12














        17












        17








        17







        Another option would be to call the base constructor that takes a DbContextOptions:



        public BooksContext(string connectionString) : base(GetOptions(connectionString))
        {
        }

        private static DbContextOptions GetOptions(string connectionString)
        {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
        }





        share|improve this answer















        Another option would be to call the base constructor that takes a DbContextOptions:



        public BooksContext(string connectionString) : base(GetOptions(connectionString))
        {
        }

        private static DbContextOptions GetOptions(string connectionString)
        {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 28 '18 at 6:14









        Sharkz

        400722




        400722










        answered Mar 31 '17 at 11:09









        Ricardo PeresRicardo Peres

        7,69222948




        7,69222948








        • 1





          had to change this to base but great solution!

          – aherrick
          Oct 18 '18 at 12:56











        • And how can i use this for oracle database ?, there is no UseOracle or somthing like that..

          – Terai
          Jan 7 at 12:56






        • 1





          Microsoft does not provide one for Oracle, you need to use a third-party. Depending on it, the extension method may be different. Please see docs.microsoft.com/en-us/ef/core/providers.

          – Ricardo Peres
          Jan 7 at 13:12














        • 1





          had to change this to base but great solution!

          – aherrick
          Oct 18 '18 at 12:56











        • And how can i use this for oracle database ?, there is no UseOracle or somthing like that..

          – Terai
          Jan 7 at 12:56






        • 1





          Microsoft does not provide one for Oracle, you need to use a third-party. Depending on it, the extension method may be different. Please see docs.microsoft.com/en-us/ef/core/providers.

          – Ricardo Peres
          Jan 7 at 13:12








        1




        1





        had to change this to base but great solution!

        – aherrick
        Oct 18 '18 at 12:56





        had to change this to base but great solution!

        – aherrick
        Oct 18 '18 at 12:56













        And how can i use this for oracle database ?, there is no UseOracle or somthing like that..

        – Terai
        Jan 7 at 12:56





        And how can i use this for oracle database ?, there is no UseOracle or somthing like that..

        – Terai
        Jan 7 at 12:56




        1




        1





        Microsoft does not provide one for Oracle, you need to use a third-party. Depending on it, the extension method may be different. Please see docs.microsoft.com/en-us/ef/core/providers.

        – Ricardo Peres
        Jan 7 at 13:12





        Microsoft does not provide one for Oracle, you need to use a third-party. Depending on it, the extension method may be different. Please see docs.microsoft.com/en-us/ef/core/providers.

        – Ricardo Peres
        Jan 7 at 13:12













        13














        Generally you are going to want to read it from config at start-up, and then use the connection string to configure an Entity Framework DbContext service for your process.



        1) Add a line to your appsettings.json:



        "DbConnectionString": "Server=s;Database=db;Trusted_Connection=True;",


        2) Read the line in you Startup.cs class (after the Startup method is called to build the Configuration - so usually in the ConfigureServices method) like this:



        var connection = Configuration["DbConnectionString"];


        3) If using Entity Framework add a database context service (MyDbContext is the context class generated by EF). You also want to tell the built-in dependency injection how to instantiate your database context:



        services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));
        services.AddScoped<IMyDbContext, MyDbContext>();


        Where IMyDbContext is (at it's simplist) just an interface you've extracted from your MyDbContext



        4) Now you can define your controller to take a MyDbContext and the DI will take care of building it and passing it in when the controller is invoked:



        public MyController(IMyDbContext context)
        {
        _context = context // store for later use
        }





        share|improve this answer






























          13














          Generally you are going to want to read it from config at start-up, and then use the connection string to configure an Entity Framework DbContext service for your process.



          1) Add a line to your appsettings.json:



          "DbConnectionString": "Server=s;Database=db;Trusted_Connection=True;",


          2) Read the line in you Startup.cs class (after the Startup method is called to build the Configuration - so usually in the ConfigureServices method) like this:



          var connection = Configuration["DbConnectionString"];


          3) If using Entity Framework add a database context service (MyDbContext is the context class generated by EF). You also want to tell the built-in dependency injection how to instantiate your database context:



          services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));
          services.AddScoped<IMyDbContext, MyDbContext>();


          Where IMyDbContext is (at it's simplist) just an interface you've extracted from your MyDbContext



          4) Now you can define your controller to take a MyDbContext and the DI will take care of building it and passing it in when the controller is invoked:



          public MyController(IMyDbContext context)
          {
          _context = context // store for later use
          }





          share|improve this answer




























            13












            13








            13







            Generally you are going to want to read it from config at start-up, and then use the connection string to configure an Entity Framework DbContext service for your process.



            1) Add a line to your appsettings.json:



            "DbConnectionString": "Server=s;Database=db;Trusted_Connection=True;",


            2) Read the line in you Startup.cs class (after the Startup method is called to build the Configuration - so usually in the ConfigureServices method) like this:



            var connection = Configuration["DbConnectionString"];


            3) If using Entity Framework add a database context service (MyDbContext is the context class generated by EF). You also want to tell the built-in dependency injection how to instantiate your database context:



            services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));
            services.AddScoped<IMyDbContext, MyDbContext>();


            Where IMyDbContext is (at it's simplist) just an interface you've extracted from your MyDbContext



            4) Now you can define your controller to take a MyDbContext and the DI will take care of building it and passing it in when the controller is invoked:



            public MyController(IMyDbContext context)
            {
            _context = context // store for later use
            }





            share|improve this answer















            Generally you are going to want to read it from config at start-up, and then use the connection string to configure an Entity Framework DbContext service for your process.



            1) Add a line to your appsettings.json:



            "DbConnectionString": "Server=s;Database=db;Trusted_Connection=True;",


            2) Read the line in you Startup.cs class (after the Startup method is called to build the Configuration - so usually in the ConfigureServices method) like this:



            var connection = Configuration["DbConnectionString"];


            3) If using Entity Framework add a database context service (MyDbContext is the context class generated by EF). You also want to tell the built-in dependency injection how to instantiate your database context:



            services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));
            services.AddScoped<IMyDbContext, MyDbContext>();


            Where IMyDbContext is (at it's simplist) just an interface you've extracted from your MyDbContext



            4) Now you can define your controller to take a MyDbContext and the DI will take care of building it and passing it in when the controller is invoked:



            public MyController(IMyDbContext context)
            {
            _context = context // store for later use
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Aug 10 '16 at 18:24

























            answered Aug 10 '16 at 18:12









            PeterPeter

            1,33411839




            1,33411839























                4














                IMO best practice:



                add to your configuration.json:



                     "ConnectionStrings": {
                "BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
                }


                and to initialize section:



                services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));





                share|improve this answer




























                  4














                  IMO best practice:



                  add to your configuration.json:



                       "ConnectionStrings": {
                  "BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
                  }


                  and to initialize section:



                  services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));





                  share|improve this answer


























                    4












                    4








                    4







                    IMO best practice:



                    add to your configuration.json:



                         "ConnectionStrings": {
                    "BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
                    }


                    and to initialize section:



                    services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));





                    share|improve this answer













                    IMO best practice:



                    add to your configuration.json:



                         "ConnectionStrings": {
                    "BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
                    }


                    and to initialize section:



                    services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 31 '17 at 10:05









                    Timur LemeshkoTimur Lemeshko

                    1,2811123




                    1,2811123























                        -1














                        So I searched all over for a solution to my issue which was I needed to dynamically connect to a database based on data that I do not have until time to do the connecting. Basically, dynamic context. I did not have the data being passed on the URL, and I did not have a short list of possible databases to attach to). So, here is my solution to the issue posed. This code will allow you to use the appsettings.json file to define the connection string with a placeholder to be replaced at run time by the code. This can be done within a controller or some other class as you see fit.



                        I am using both a static context and a dynamic context but you could use dynamic only.



                        Hopefully someone will stumble upon this and say thank god...although probably just as likely someone will say, this guy is an idiot. Either way, enjoy.



                        using System;
                        using System.Globalization;
                        using System.Linq;
                        using Microsoft.Extensions.Configuration;

                        namespace CallCenter.Repositories
                        {
                        public class TestRepository : ITestRepository
                        {
                        private readonly InsuranceContext _context;
                        public TestRepository InsuranceContext context)
                        {
                        _context = context;
                        }

                        public void Add(string passedInStringWhichTellsWhatDatabaseToUse)
                        {
                        var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");

                        var configuration = builder.Build();
                        var connectionString = configuration.GetConnectionString("DefaultConnection");


                        var agencyContext = new AgencyContext(connectionString.Replace("Database=replacethisstring", "Database=" + passedInStringWhichTellsWhatDatabaseToUse));

                        var company = agencyContext.Companys.FirstOrDefault(x => x.ColumnNameInDb == "xyz");
                        if (company != null)
                        {
                        companyId = company.CompanyId.ToString();
                        }

                        ... your other code here which could include the using the passed in _context from the injected code (or you could not have any context passed in and just use dynamic context
                        }

                        }
                        }
                        }

                        //The AgencyContext class would look like this:

                        using Microsoft.EntityFrameworkCore;

                        namespace CallCenter.Entities
                        {
                        public class AgencyContext : DbContext
                        {
                        public AgencyContext(string connectionString) : base(GetOptions(connectionString))
                        {

                        }

                        private static DbContextOptions GetOptions(string connectionString)
                        {
                        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
                        }

                        public DbSet<Companys> Companys { get; set; }
                        }
                        }

                        //The startup.c IServiceProvider module has this:

                        public IServiceProvider ConfigureServices(IServiceCollection services)
                        {
                        services.AddOptions();

                        services.AddDbContext<InsuranceContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.UseRowNumberForPaging()));
                        services.AddScoped<ITestRepository , TestRepository >();
                        ....
                        }


                        And finally the appsettings.jason file would have this in it:



                        {
                        "ConnectionStrings": {
                        "DefaultConnection": "Server=yourservername;Database=replacethisstring;User ID=youruserid;Password=yourpassword;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
                        }
                        }





                        share|improve this answer




























                          -1














                          So I searched all over for a solution to my issue which was I needed to dynamically connect to a database based on data that I do not have until time to do the connecting. Basically, dynamic context. I did not have the data being passed on the URL, and I did not have a short list of possible databases to attach to). So, here is my solution to the issue posed. This code will allow you to use the appsettings.json file to define the connection string with a placeholder to be replaced at run time by the code. This can be done within a controller or some other class as you see fit.



                          I am using both a static context and a dynamic context but you could use dynamic only.



                          Hopefully someone will stumble upon this and say thank god...although probably just as likely someone will say, this guy is an idiot. Either way, enjoy.



                          using System;
                          using System.Globalization;
                          using System.Linq;
                          using Microsoft.Extensions.Configuration;

                          namespace CallCenter.Repositories
                          {
                          public class TestRepository : ITestRepository
                          {
                          private readonly InsuranceContext _context;
                          public TestRepository InsuranceContext context)
                          {
                          _context = context;
                          }

                          public void Add(string passedInStringWhichTellsWhatDatabaseToUse)
                          {
                          var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");

                          var configuration = builder.Build();
                          var connectionString = configuration.GetConnectionString("DefaultConnection");


                          var agencyContext = new AgencyContext(connectionString.Replace("Database=replacethisstring", "Database=" + passedInStringWhichTellsWhatDatabaseToUse));

                          var company = agencyContext.Companys.FirstOrDefault(x => x.ColumnNameInDb == "xyz");
                          if (company != null)
                          {
                          companyId = company.CompanyId.ToString();
                          }

                          ... your other code here which could include the using the passed in _context from the injected code (or you could not have any context passed in and just use dynamic context
                          }

                          }
                          }
                          }

                          //The AgencyContext class would look like this:

                          using Microsoft.EntityFrameworkCore;

                          namespace CallCenter.Entities
                          {
                          public class AgencyContext : DbContext
                          {
                          public AgencyContext(string connectionString) : base(GetOptions(connectionString))
                          {

                          }

                          private static DbContextOptions GetOptions(string connectionString)
                          {
                          return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
                          }

                          public DbSet<Companys> Companys { get; set; }
                          }
                          }

                          //The startup.c IServiceProvider module has this:

                          public IServiceProvider ConfigureServices(IServiceCollection services)
                          {
                          services.AddOptions();

                          services.AddDbContext<InsuranceContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.UseRowNumberForPaging()));
                          services.AddScoped<ITestRepository , TestRepository >();
                          ....
                          }


                          And finally the appsettings.jason file would have this in it:



                          {
                          "ConnectionStrings": {
                          "DefaultConnection": "Server=yourservername;Database=replacethisstring;User ID=youruserid;Password=yourpassword;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
                          }
                          }





                          share|improve this answer


























                            -1












                            -1








                            -1







                            So I searched all over for a solution to my issue which was I needed to dynamically connect to a database based on data that I do not have until time to do the connecting. Basically, dynamic context. I did not have the data being passed on the URL, and I did not have a short list of possible databases to attach to). So, here is my solution to the issue posed. This code will allow you to use the appsettings.json file to define the connection string with a placeholder to be replaced at run time by the code. This can be done within a controller or some other class as you see fit.



                            I am using both a static context and a dynamic context but you could use dynamic only.



                            Hopefully someone will stumble upon this and say thank god...although probably just as likely someone will say, this guy is an idiot. Either way, enjoy.



                            using System;
                            using System.Globalization;
                            using System.Linq;
                            using Microsoft.Extensions.Configuration;

                            namespace CallCenter.Repositories
                            {
                            public class TestRepository : ITestRepository
                            {
                            private readonly InsuranceContext _context;
                            public TestRepository InsuranceContext context)
                            {
                            _context = context;
                            }

                            public void Add(string passedInStringWhichTellsWhatDatabaseToUse)
                            {
                            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");

                            var configuration = builder.Build();
                            var connectionString = configuration.GetConnectionString("DefaultConnection");


                            var agencyContext = new AgencyContext(connectionString.Replace("Database=replacethisstring", "Database=" + passedInStringWhichTellsWhatDatabaseToUse));

                            var company = agencyContext.Companys.FirstOrDefault(x => x.ColumnNameInDb == "xyz");
                            if (company != null)
                            {
                            companyId = company.CompanyId.ToString();
                            }

                            ... your other code here which could include the using the passed in _context from the injected code (or you could not have any context passed in and just use dynamic context
                            }

                            }
                            }
                            }

                            //The AgencyContext class would look like this:

                            using Microsoft.EntityFrameworkCore;

                            namespace CallCenter.Entities
                            {
                            public class AgencyContext : DbContext
                            {
                            public AgencyContext(string connectionString) : base(GetOptions(connectionString))
                            {

                            }

                            private static DbContextOptions GetOptions(string connectionString)
                            {
                            return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
                            }

                            public DbSet<Companys> Companys { get; set; }
                            }
                            }

                            //The startup.c IServiceProvider module has this:

                            public IServiceProvider ConfigureServices(IServiceCollection services)
                            {
                            services.AddOptions();

                            services.AddDbContext<InsuranceContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.UseRowNumberForPaging()));
                            services.AddScoped<ITestRepository , TestRepository >();
                            ....
                            }


                            And finally the appsettings.jason file would have this in it:



                            {
                            "ConnectionStrings": {
                            "DefaultConnection": "Server=yourservername;Database=replacethisstring;User ID=youruserid;Password=yourpassword;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
                            }
                            }





                            share|improve this answer













                            So I searched all over for a solution to my issue which was I needed to dynamically connect to a database based on data that I do not have until time to do the connecting. Basically, dynamic context. I did not have the data being passed on the URL, and I did not have a short list of possible databases to attach to). So, here is my solution to the issue posed. This code will allow you to use the appsettings.json file to define the connection string with a placeholder to be replaced at run time by the code. This can be done within a controller or some other class as you see fit.



                            I am using both a static context and a dynamic context but you could use dynamic only.



                            Hopefully someone will stumble upon this and say thank god...although probably just as likely someone will say, this guy is an idiot. Either way, enjoy.



                            using System;
                            using System.Globalization;
                            using System.Linq;
                            using Microsoft.Extensions.Configuration;

                            namespace CallCenter.Repositories
                            {
                            public class TestRepository : ITestRepository
                            {
                            private readonly InsuranceContext _context;
                            public TestRepository InsuranceContext context)
                            {
                            _context = context;
                            }

                            public void Add(string passedInStringWhichTellsWhatDatabaseToUse)
                            {
                            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");

                            var configuration = builder.Build();
                            var connectionString = configuration.GetConnectionString("DefaultConnection");


                            var agencyContext = new AgencyContext(connectionString.Replace("Database=replacethisstring", "Database=" + passedInStringWhichTellsWhatDatabaseToUse));

                            var company = agencyContext.Companys.FirstOrDefault(x => x.ColumnNameInDb == "xyz");
                            if (company != null)
                            {
                            companyId = company.CompanyId.ToString();
                            }

                            ... your other code here which could include the using the passed in _context from the injected code (or you could not have any context passed in and just use dynamic context
                            }

                            }
                            }
                            }

                            //The AgencyContext class would look like this:

                            using Microsoft.EntityFrameworkCore;

                            namespace CallCenter.Entities
                            {
                            public class AgencyContext : DbContext
                            {
                            public AgencyContext(string connectionString) : base(GetOptions(connectionString))
                            {

                            }

                            private static DbContextOptions GetOptions(string connectionString)
                            {
                            return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
                            }

                            public DbSet<Companys> Companys { get; set; }
                            }
                            }

                            //The startup.c IServiceProvider module has this:

                            public IServiceProvider ConfigureServices(IServiceCollection services)
                            {
                            services.AddOptions();

                            services.AddDbContext<InsuranceContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.UseRowNumberForPaging()));
                            services.AddScoped<ITestRepository , TestRepository >();
                            ....
                            }


                            And finally the appsettings.jason file would have this in it:



                            {
                            "ConnectionStrings": {
                            "DefaultConnection": "Server=yourservername;Database=replacethisstring;User ID=youruserid;Password=yourpassword;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
                            }
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 18 at 21:44









                            Terry GilmanTerry Gilman

                            11




                            11






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38878140%2fhow-can-i-implement-dbcontext-connection-string-in-net-core%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                                Calculate evaluation metrics using cross_val_predict sklearn

                                Insert data from modal to MySQL (multiple modal on website)