0

I got this error "Format of the initialization string does not conform to specification starting at index 0." while migrating.

my connection string given in

appsettings.json

"ConnectionStrings": {
 "DefaultConnection": "Data Source=LAPTOP-P08F3TG1/ckary;Initial Catalog=Product;Integrated Security=True"
 },

ApplicationDbcontext.cs

 public class ApplicationDbContext:DbContext
    {
        public DbSet<Login> Logins { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("DefaultConnection");
        }

please help to findout my mistake

correct answer or format to solve my error

Qing Guo
  • 6,041
  • 1
  • 2
  • 10

3 Answers3

1

Try:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("appsettings.json")
                .Build();
            optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
        }
Qing Guo
  • 6,041
  • 1
  • 2
  • 10
0

Could you try this?

"ConnectionStrings": {
 "DefaultConnection": "Data Source=LAPTOP-P08F3TG1\ckary;Initial 
  Catalog=Product;Integrated Security=True"
 }
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 22 '23 at 10:19
0

When using JSON based configuration you first need to ensure that your string values are encoded correctly, many examples on connection strings will assume XML based configuration that has different encoding rules.

Specifically, for usernames and data sources (servers) that commonly contain the back-slash character \, in JSON this is an escape character itself, so we need to escape it like this:

LAPTOP-P08F3TG1\\ckary

"ConnectionStrings": {
      "DefaultConnection": "Data Source=LAPTOP-P08F3TG1\\ckary;Initial Catalog=Product;Integrated Security=True"
    }

this answer by Quing Guo should help if your appsettings.json file is not in the default location or your project has been upgraded to ASP.Net Core from a legacy codebase.

Chris Schaller
  • 13,704
  • 3
  • 43
  • 81