使用多个DbContext的实体框架核心

乔·希格利(Joe Higley):

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

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

似乎这是因为我试图使我的PartsDbContext使用与与Identity一起使用的ApplicationDbContext相同的数据库。我需要知道如何设置第二个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)
    {
    }
}

启动文件

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设置为与Entity Framework Core一起使用,以EF-Core会自动创建数据库的方式。

乔·希格利(Joe Higley):

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

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

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

我发现了这一点,因为这是使我的ApplicationDbContext重新工作所要做的事情,事实证明,当您使用个人用户身份验证在Visual Studio中创建新的MVC Core Web应用程序时,此步骤已为您完成。

因此,基本上,添加更多DbContext的步骤是:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章