如何解决在ASP.NET Core Entity Framework中未初始化ConnectionString属性

huangapple go评论67阅读模式
英文:

How to resolve The ConnectionString property has not been Initialized in ASP.NET Core Entity Framework

问题

The error message "The ConnectionString property has not been Initialized" suggests that the Entity Framework Core is unable to find the connection string for your database.

In your appsettings.json, it appears that the connection string is defined under "ConnectionStrings" with the name "DefaultDbConnection." However, in your DbContext class, when configuring the DbContext using UseSqlServer, you are passing "Name=DefaultDbConnection" as the connection string.

To resolve this issue, make sure you pass the correct connection string to UseSqlServer. Modify the OnConfiguring method in your DefaultDbContext class like this:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        string connStr = Configuration.GetConnectionString("DefaultDbConnection");
        optionsBuilder.UseSqlServer(connStr);
    }
}

This change ensures that Entity Framework Core uses the correct connection string from your appsettings.json file when initializing the DbContext. After making this change, try running the update-database command again in the Package Console Manager.

英文:

ASP.NET Core-7 Web API application, I am implementing Entity Framework. Then I have this code:

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());
    }
}

My appsettings.json is as shown below:

  "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"
  },

Extension:

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);
        });
    }
}

Program.cs:

builder.Services.AddDbContextAndConfigurations(environment, configuration);

However, when I did:

update-database -verbose in the Package Console Manager, I got this error:

> The ConnectionString property has not been Initialized

How do I resolve this?

答案1

得分: 1

传递给 UseSqlServer 的字符串缺少键“ConnectionStrings”:

    services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer("name=ConnectionStrings:DefaultDbConnection"));
英文:

The string you are passing to the UseSqlServer is the missing the key ConnectionStrings

    services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer("name=ConnectionStrings:DefaultDbConnection"));

ref; https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/#dbcontext-in-dependency-injection-for-aspnet-core

答案2

得分: 0

如果您使用 IConfiguration.GetConnectionString("xx") 来获取 ConnectionStrings 的值,您只需要传递键值

"ConnectionStrings": {
    "key": "value"
}

而不是传递 Name=key。因此,在您的扩展方法中,您需要修改代码如下:

connStr = config.GetConnectionString("DefaultDbConnection")
英文:

If you use IConfiguration.GetConnectionString("xx") to get the value of ConnectionStrings, You just need to pass the key in

"ConnectionStrings": {
    "key": "value"
  }

instead of passing Name=key, So here in your Extension method, you need to modify the code like:

connStr = config.GetConnectionString("DefaultDbConnection")

huangapple
  • 本文由 发表于 2023年5月17日 15:10:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定