【发布时间】:2021-08-12 06:30:24
【问题描述】:
我正在使用 .Net core 2.1 + EF Core 来构建 WebApi。基于此讨论:Entity Framework: One Database, Multiple DbContexts. Is this a bad idea? 和来自 DDD 的有界上下文概念我想为我的应用程序中的不同功能创建多个 DbContext。 Julie Lerman 在 PluralSight.com 上提供了一些资源,但其中不包括 .net core 中的依赖注入。到目前为止,我做了这样的事情:
var connectionString = Configuration.GetConnectionString("DatabaseName");
services.AddDbContext<DatabaseContext>(options =>
options.UseSqlServer(connectionString, optionsBuilder =>
optionsBuilder.MigrationsAssembly("Database.Migrations")));
services.AddDbContext<ProductContext>(options =>
options.UseSqlServer(connectionString));
services.AddDbContext<CountryContext>(options =>
options.UseSqlServer(connectionString));
这里 DatabaseContext 是用于 EF Core 迁移的上下文(实际上并不查询数据),ProductContext 和 CountryContext 是我用于数据操作的两个上下文。我的问题是:
- 这是正确的做法吗?重复使用相同的连接字符串感觉有点奇怪
- 感觉就像我将使用 2 个单独的连接(并且这种连接会增加),这是否会导致将来出现一些数据访问问题、锁定、并发性等?
更新(2020-01-09)
我已经使用它一年多了。到目前为止没有任何与数据库连接相关的问题。也计划在未来的项目中使用这种方法。
【问题讨论】:
标签: entity-framework entity-framework-core dbcontext asp.net-core-2.1