Core中的DbContext类

Core中的DbContext类

本文介绍了.Net Core中的DbContext类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我被错误提示卡住了:

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

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

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

ExampleModelWrapper是一个模型.

ExampleModelWrapper is a model.

我在堆栈溢出中提到了以下问题:如何在.NET Core中实现DbContext连接字符串?

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

我在appsettings.json中有连接字符串:

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

我已经在startup.cs中提供了服务:

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

可能是上述错误的原因.我认为已成功建立到数据库的连接,因为该连接正在为Identity Db的登录和注册流程工作.我也对如何或在何处更改身份Db的连接感到困惑.感谢帮助,谢谢!!

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

推荐答案

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

到以下:

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

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

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

这篇关于.Net Core中的DbContext类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:47