.Net Core中的DbContext类

时间:2018-10-05 08:55:58

标签: asp.net-core .net-core entity-framework-core asp.net-core-2.0

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

我被错误提示卡住了:

  

无法从“字符串”转换为   'Microsoft.EntityFrameworkCore.DbContextOptions'

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

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

ExampleModelWrapper是一个模型。

我在堆栈溢出中提到了以下问题: How can I implement DbContext Connection String in .NET Core?

我在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的登录和注册流程工作。我也对如何或在何处更改身份Db的连接感到困惑。感谢帮助,谢谢!!

1 个答案:

答案 0 :(得分:3)

您需要在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

相关问题