我正在尝试诊断我的数据库上下文配置中的问题,但是它永远不会在那里遇到刹车点,因为这是我发出 dotnet ef 更新命令。例如,我想要一些方法来调试我正在使用 ef 7 和 .net 7
中的内容protected override void OnConfiguring(DbContextOptionsBuilder options)
{
var test2 = _configuration.GetConnectionString("DefaultConnection");
options.UseSqlServer(test2);
options.EnableSensitiveDataLogging();
}
这是我的背景
public class StubsDBContext :IdentityDbContext<ApplicationUser>
{
private readonly IConfiguration _configuration;
public StubsDBContext()
{
}
public StubsDBContext(DbContextOptions<StubsDBContext> options , IConfiguration configuration) : base(options)
{
_configuration = configuration;
}
public DbSet<Stub> Stubs { get; set; }
public DbSet<Stub> Stubs3 { get; set; }
public string GetConnectionString()
{
return ConnectionStrings.DefaultConnection;
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
var test2 = _configuration.GetConnectionString("DefaultConnection");
options.UseSqlServer(test2);
options.EnableSensitiveDataLogging();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
我从我的 program.cs 添加它,因为此时测试确实检索到正确的连接字符串
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
{
string? TEST = configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<StubsDBContext>(options =>
options.UseSqlServer(TEST,
builder => builder.MigrationsAssembly(typeof(StubsDBContext).Assembly.FullName)));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<StubsDBContext>()
.AddDefaultTokenProviders();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
return services;
}
应用设置
{
"ConnectionStrings": {
"DefaultConnection": "removed for security"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
},
"AppSettings": {
"Secret": "removed for security"
}
}
}
这是我的程序.cs
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var provider = builder.Services.BuildServiceProvider();
var config = provider.GetService<IConfiguration>();
_configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
builder.Services.AddInfrastructureServices(builder.Configuration);
//+ builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Add services to the container.
// Add services to the container.
builder.Services.AddControllers();
var appSettingsSection = config.GetSection("AppSettings");
builder.Services.Configure<AppSettings>(appSettingsSection);
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
...removed for length
}