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

71,710

Solution 1

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;
}

Solution 2

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
}

Solution 3

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))));

Solution 4

An easy way is, just to use an optionbuilder to get the Context:

    public static MyDbContext GetMyDbContext(string databaseName)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();

        optionsBuilder.UseSqlServer($@"Data Source=.\SqlExpress;Initial Catalog={databaseName};Integrated Security=True");

        return new MyDbContext(optionsBuilder.Options);

    }

Solution 5

Startup.cs for static connection

services.AddScoped<MyContext>(_ => new MyContext(Configuration.GetConnectionString("myDB")));

Table1Repository.cs for dynamic connection

using (var _context = new MyContext(@"server=....){
context.Table1....
}

MyContext.cs

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

private static DbContextOptions GetOptions(string connectionString)
{
    return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}
Share:
71,710
Kemal Tezer Dilsiz
Author by

Kemal Tezer Dilsiz

https://www.couchsurfing.com/people/ktdilsiz

Updated on July 09, 2022

Comments

  • Kemal Tezer Dilsiz
    Kemal Tezer Dilsiz almost 2 years

    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?

  • aherrick
    aherrick over 5 years
    had to change this to base but great solution!
  • Terai
    Terai over 5 years
    And how can i use this for oracle database ?, there is no UseOracle or somthing like that..
  • Ricardo Peres
    Ricardo Peres over 5 years
    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.
  • Tobias J
    Tobias J over 4 years
    If you need to get a strongly-typed DbContextOptions<TContext>, you need to use new DbContextOptionsBuilder<BooksContext>.
  • Vamos
    Vamos almost 3 years
    It's work. This answer helps me a lot. Thanks.