Search code examples
c#asp.net.netentity-framework

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


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?


Solution

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