实体框架核心使用多个DbContexts

问题描述 投票:15回答:1

我有一个问题,当我尝试访问我的PartsDbContext中的字段时,我收到以下错误:

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

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

我已经尝试创建第二个连接字符串,但这会让我犯这个错误:

System.Data.SqlClient.SqlException:'无法打开登录请求的数据库“PartsDb”。登录失败。用户'DESKTOP-4VPU567 \ higle'登录失败。'

这是我的代码:

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();是出现错误的地方。

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

c# entity-framework-core dbcontext asp.net-core-1.1
1个回答
22
投票

我想到了。这主要是因为我不小心删除了Identity正在使用的数据库,我需要弄清楚如何将其恢复。

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

  1. Add-Migration init -Context PartsDbContext
  2. Update-Database -Context PartsDbContext

我找到了这个,因为这是我必须要做的才能让我的ApplicationDbContext再次工作,结果是当你使用个人用户身份验证在Visual Studio中创建一个新的MVC核心Web应用程序时,这一步就完成了。

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

  1. 创建一个DbContext类
  2. 在appsettings.json中为该DbContext创建一个Connection字符串
  3. 将DbContext添加到Startup.cs中的已配置服务
  4. 在将使用它的控制器中设置DbContext。
  5. 打开包管理器并运行上面的2行。 (如果“-Context”不起作用,请尝试“--context”
  6. 运行你的程序,让EntityFrameworkCore处理剩下的事情。
© www.soinside.com 2019 - 2024. All rights reserved.