Question

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!!

1
0
10/5/2018 9:15:42 AM

Accepted Answer

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.

4
10/5/2018 9:11:05 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow