使用多个DbContext的实体框架核心 [英] Entity Framework Core Using multiple DbContexts
问题描述
我遇到一个问题,当我尝试访问我的PartsDbContext中的字段时,出现以下错误:
I'm having a problem that when I try to access a field in my PartsDbContext I get the following error:
系统。 Data.SqlClient.SqlException:'无效的对象名称'fieldName'
System.Data.SqlClient.SqlException: 'Invalid object name 'fieldName''
似乎这是因为我试图使我的PartsDbContext使用与与Identity一起使用的ApplicationDbContext相同的数据库。我需要知道如何设置第二个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-4VPU567\higle'的登录失败。
System.Data.SqlClient.SqlException: 'Cannot open database "PartsDb" requested by the login. The login failed. Login failed for user '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设置为与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:
-
添加迁移init-上下文PartsDbContext
-
更新数据库-Context PartsDbContext
Add-Migration init -Context PartsDbContext
Update-Database -Context PartsDbContext
我发现了这一点,因为这是使ApplicationDbContext再次工作所要做的,事实证明,当您创建新的MVC Core Web Application时,此步骤已为您完成在Visual Studio中使用个人用户身份验证。
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:
- 创建DbContext类
- 在 appsettings.json 中为该DbContext创建连接字符串在 Startup.cs
- 将DbContext添加到已配置的服务中。在将使用它的控制器中设置DbContext。
- 打开软件包管理器并运行上面的2行。 (如果 -Context不起作用,请尝试 --context
- 运行程序,让EntityFrameworkCore负责其余的工作。
- Create a DbContext Class
- Create a Connection string for that DbContext in appsettings.json
- Add the DbContext to your configured services in Startup.cs
- Setup the DbContext in the controllers that will use it.
- Open the package manager and run the 2 lines above. (if "-Context" doesn't work try "--context"
- Run your program and let EntityFrameworkCore take care of the rest.
这篇关于使用多个DbContext的实体框架核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!