Приложение веб-API ASP.NET Core-7, я реализую Entity Framework. Тогда у меня есть этот код:
public partial class DefaultDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IDateTime _dateTime;
public DefaultDbContext(DbContextOptions<DefaultDbContext> options) : base(options)
{
}
public DefaultDbContext(DbContextOptions<DefaultDbContext> options,
ICurrentUserService currentUserService, IDateTime dateTime)
: base(options)
{
_currentUserService = currentUserService;
_dateTime = dateTime;
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<ApplicationRole> ApplicationRoles { get; set; }
public DbSet<Merchant> Merchants { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Name=DefaultDbConnection");
}
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(typeof(DefaultDbContext).Assembly);
base.OnModelCreating(builder);
builder.ApplyConfiguration(new MerchantConfigurations());
builder.ApplyConfiguration(new ApplicationUserConfigurations());
builder.ApplyConfiguration(new ApplicationUserRoleConfigurations());
builder.ApplyConfiguration(new IdentityRoleClaimConfigurations());
builder.ApplyConfiguration(new IdentityUserClaimConfigurations());
builder.ApplyConfiguration(new IdentityUserLoginConfigurations());
builder.ApplyConfiguration(new IdentityUserClaimConfigurations());
builder.ApplyConfiguration(new ApplicationRoleConfigurations());
builder.ApplyConfiguration(new IdentityUserTokenConfigurations());
}
}
Мой appsettings.json показан ниже:
"ConnectionStrings": {
"DefaultDbConnection": "Server=141.32.54.131,62762;Database=MyDB;Min Pool Size=100;Max Pool Size=1000;User Id=username; Password=password; trustServerCertificate=true"
},
Расширение:
public static class ConnectionConfiguration
{
public static void AddDbContextAndConfigurations(this IServiceCollection services, IWebHostEnvironment env, IConfiguration config)
{
services.AddDbContext<DefaultDbContext>(options =>
{
string connStr;
connStr = config.GetConnectionString("Name=DefaultDbConnection");
options.UseSqlServer(connStr);
});
}
}
Программа.cs:
builder.Services.AddDbContextAndConfigurations(environment, configuration);
Однако, когда я это сделал:
update-database -verbose в диспетчере консоли пакетов я получил эту ошибку:
Свойство ConnectionString не было инициализировано
Как решить эту проблему?





В строке, которую вы передаете UseSqlServer, отсутствует ключ ConnectionStrings
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer("name=ConnectionStrings:DefaultDbConnection"));
Я уже сделал это. Смотрите обновленный код. Но все еще не работает
Используйте Configuration.GetConnectionString, чтобы получить строку подключения из вашего appsettings.json в вашей программе/классе запуска.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DefaultDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("DefaultDbConnection"));
});
}
Если вы используете IConfiguration.GetConnectionString("xx"), чтобы получить значение ConnectionStrings, вам просто нужно передать ключ в
"ConnectionStrings": {
"key": "value"
}
вместо передачи Name=key, поэтому здесь, в вашем методе расширения, вам нужно изменить код, например:
connStr = config.GetConnectionString("DefaultDbConnection")
Не могли бы вы предоставить код регистрации dbcontext в
program.cs?