单独程序集中的迁移 如何避免硬编码的连接字符串?



我正在编写 ASP.NET 核心和实体框架核心应用程序,我想将数据访问层存储在单独的程序集中,所以我遵循了本教程:http://www.michael-whelan.net/ef-core-101-migrations-in-separate-assembly/

但我也想避免硬编码连接字符串。我尝试将其存储在 JSON 配置文件或作为环境变量并使用ConfigurationBuilder获取它,但是当使用命令行迁移工具时dotnet ef migrations这些都不可用。 有没有办法解决这个问题?我使用的是 .NET Core 和 EF Core 的 1.0.1 版本。

为了解决这个问题,我创建了一个类库,仅用于使用从我的 DbContext 派生的 DbContext 进行迁移,但使用硬连接字符串。

using Microsoft.EntityFrameworkCore;
namespace ChatLe.Repository.Identity.SqlServer
{
public class ChatLeIdentityDbContext: ChatLe.Models.ChatLeIdentityDbContext
{
public ChatLeIdentityDbContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\mssqllocaldb;Database=chatle;Trusted_Connection=True;MultipleActiveResultSets=true");
base.OnConfiguring(optionsBuilder);
}
}
}

然后我像这样启动 ef 工具命令:

  • 添加迁移运行dotnet ef --startup-project {path to my startup project} migrations add login-activity --context ChatLe.Repository.Identity.SqlServer.ChatLeIdentityDbContext
  • 升级数据库运行dotnet ef --startup-project {path to my startup project} database update --context ChatLe.Repository.Identity.SqlServer.ChatLeIdentityDbContext

阅读我的 git hub 项目的完整示例:https://github.com/aguacongas/chatle/tree/develop/src/ChatLe.Repository.Identity.SqlServer

最新更新