.Net Core 中的 DbContext class

DbContext class in .Net Core

大家好,我正在尝试从 Asp.Net MVC 5 迁移到 .Net Core 2.0 Web 应用程序。

我遇到了一条错误消息:

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

当我将鼠标悬停在 class 上时出现上述错误:

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

ExampleModelWrapper 是一个模型。

我在堆栈溢出中提到了以下问题:

我在 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"
    }
  }
}

我在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();
        }

出现上述错误的原因可能是什么。我相信已成功建立与数据库的连接,因为它正在为 Identity Db.I 的登录和注册流程工作,我也对如何或在何处更改 Identity Db 的连接感到困惑。帮助赞赏,谢谢!!

您需要在 DbContext

中使用以下构造函数
public ExampleModelWrapper (DbContextOptions<ExampleModelWrapper> options)
    : base(options)
{
}

在您的启动中,您需要修改以下内容:

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

以下内容:

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

基本上,您需要指定您需要使用的DbContext