Search code examples
asp.net-core-mvcconnection-string

The connection string property has not been initialized, but everything is fine


Project structure: ASP.NET Core 6 MVC.

I have tried uncountable guides to solve this problem, but none of them seems to work for me.

When I run Update-Database, I get the following error:

The ConnectionString property has not been initialized

enter image description here

This is my connection string:

"connstr": "Server=COMPUTADOR\\MSSQLSERVERGERA;Database=master;Trusted_Connection=True;User Id=admin;Password=admin;"

My Program.cs code:

builder.Services.AddDbContext<MyDbContext>(options => {
       options.UseSqlServer(builder.Configuration.GetConnectionString("connstr"));
});

My DbContext:

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }
}

Solution

  • your syntax of sql string is wrong and you can can not use system master db as your database. also if you use trusted connection you can not use password. Your connection string for MS Sql server should be like this

     "DefaultConnection": "Data Source=myserverip;initial catalog=mydb;Integrated Security=False;User ID=admin;Password=admin;"