使用多个 DbContext 的实体框架核心 [英] Entity Framework Core Using multiple DbContexts

查看:21
本文介绍了使用多个 DbContext 的实体框架核心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,当我尝试访问 PartsDbContext 中的字段时,出现以下错误:

I'm having a problem that when I try to access a field in my PartsDbContext I get the following error:

System.Data.SqlClient.SqlException: '无效的对象名称 'fieldName''

System.Data.SqlClient.SqlException: 'Invalid object name 'fieldName''

这似乎是因为我试图让我的 PartsDbContext 与我的 ApplicationDbContext 使用相同的数据库,该数据库与 Identity 一起使用.我需要知道如何设置第二个 dbcontext 以与使用/创建不同数据库的 EF 核心一起使用.

It seems that this is because I'm trying to make my PartsDbContext use the same database as my ApplicationDbContext which is used with Identity. I need to know how to setup a 2nd dbcontext to work with EF core that uses/creates a different database.

我已尝试创建第二个连接字符串,但出现此错误:

I've tried creating a 2nd connection string but that gets me this error:

System.Data.SqlClient.SqlException: '无法打开登录请求的数据库PartsDb".登录失败.用户DESKTOP-4VPU567higle"登录失败.

System.Data.SqlClient.SqlException: 'Cannot open database "PartsDb" requested by the login. The login failed. Login failed for user 'DESKTOP-4VPU567higle'.'

这是我的代码:

appsettings.json

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-PrecisionCustomPC-b14db89e-86ad-4855-a17f-ac64a04339aa;Trusted_Connection=True;MultipleActiveResultSets=true",
    "PartsConnection":  "Server=(localdb)\mssqllocaldb;Database=PartsDb"
},
"Logging": {
    "IncludeScopes": false,
    "LogLevel": {
        "Default": "Warning"
    }
}

PartsDbContext.cs

public class PartsDbContext : DbContext
{
    public DbSet<PartsViewModels.Tower> Towers { get; set; }
    public DbSet<PartsViewModels.Motherboard> Motherboards { get; set; }

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

Startup.cs

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

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

    services.AddEntityFramework()
        .AddDbContext<PartsDbContext>(options =>
          options.UseSqlServer(Configuration.GetConnectionString("PartsConnection")));

    services.AddMvc();

    services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
    });

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

AdminController.cs

[Authorize(Policy = "RequireAdminRole")]
public class AdminController : Controller
{
    private readonly PartsDbContext _context;

    public AdminController(PartsDbContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Towers()
    {
        var model = _context.Towers.ToList();
        return View(model);
    }
}

var model = _context.Towers.ToList(); 是错误出现的地方.

The line var model = _context.Towers.ToList(); is where the error is showing up.

再来一次.我想设置我的 PartsDbContext 以与 Entity Framework Core 一起使用,EF-Core 将自动创建数据库.

Once again. I want to setup my PartsDbContext to work with Entity Framework Core in a way that EF-Core will automatically create the database.

推荐答案

我想通了.这主要是因为我不小心删除了 Identity 正在使用的数据库,我需要弄清楚如何取回它.

I figured it out. This mostly came about because I accidentally deleted the database that Identity was using and I needed to figure out how to get it back.

显然,我的连接字符串没有任何问题.我只需要进入包管理器并按以下顺序键入这些命令:

Apparently there's nothing wrong with my connection string the way it is. I just needed to go into the package manager and type these commands in this order:

  1. 添加迁移初始化 -Context PartsDbContext
  2. Update-Database -Context PartsDbContext

我发现了这一点,因为这是我必须做的才能让我的 ApplicationDbContext 再次工作,而且当您使用个人用户身份验证在 Visual Studio 中创建新的 MVC 核心 Web 应用程序时,这一步已为您完成.

I found this out because that is what I had to do to get my ApplicationDbContext working again and it turns out that this step is done for you when you create a new MVC Core Web Application in Visual Studio using Individual User Authentication.

所以基本上添加更多 DbContext 的步骤是:

So basically the steps for adding more DbContexts is to:

  1. 创建 DbContext 类
  2. appsettings.json
  3. 中为该 DbContext 创建一个连接字符串
  4. 将 DbContext 添加到您在 Startup.cs 中配置的服务
  5. 在将使用它的控制器中设置 DbContext.
  6. 打开包管理器并运行上面的 2 行.(如果-Context"不起作用,请尝试--context"
  7. 运行您的程序,让 EntityFrameworkCore 处理其余的事情.

这篇关于使用多个 DbContext 的实体框架核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆