Abhilash Gopalakrishna
Abhilash Gopalakrishna

Reputation: 980

DbContext class in .Net Core

Hi Guys I am trying to migrate from Asp.Net MVC 5 to .Net Core 2.0 Web Application.

I am stuck with a error saying :

Cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions'

I get the above error when I hover over the class:

 public class ExampleModelWrapper : DbContext
    {
        public ExampleModelWrapper()
            : base("name=EXAMPLE_MODEL")
        {
        }
    }

ExampleModelWrapper is a model.

I referred to the following question in stack overflow: How can I implement DbContext Connection String in .NET Core?

I have the connection string in appsettings.json:

{
  "ConnectionStrings": {
    "EXAMPLE_MODEL": "Server=(localdb)\\mssqllocaldb;Database=aspnet-Monitoring-CCA7D047-80AC-4E36-BAEA-3653D07D245A;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

I have provided the service in startup.cs:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("EXAMPLE_MODEL")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            // Add application services.
            services.AddTransient<IEmailSender, EmailSender>();

            services.AddMvc();
        }

What can be the reason for the above error. I believe a connection is being established to the database successfully ,as it is working for the login and registration flow of Identity Db.I am also stumped on how or where to change the connections for the identity Db. Help appreciated , Thank you!!

Upvotes: 1

Views: 1293

Answers (1)

Neville Nazerane
Neville Nazerane

Reputation: 7019

You need to use the following constructor in your DbContext

public ExampleModelWrapper (DbContextOptions<ExampleModelWrapper> options)
    : base(options)
{
}

Within your startup, you need to modify the following:

services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("EXAMPLE_MODEL")));

to the following:

services.AddDbContext<ExampleModelWrapper>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("EXAMPLE_MODEL")));

Basically, you need to specify the DbContext you need to use.

Upvotes: 4

Related Questions