1

I add appsettings.json in order to get connection string but I cannot get my connection string. Here is my code.

public class MovieTheaterDBContextFactory : IDesignTimeDbContextFactory<MovieTheaterDBContext>
{
    public MovieTheaterDBContext CreateDbContext(string []Args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .Build();

        var ConnectionString = configuration.GetConnectionString("MovieTheaterDBContext");
        //var ConnectionString = "Server=DESKTOPM4\\SQLEXPRESS;Database=MovieTheaterManagerment;Trusted_Connection=True;";
        var optionsBuilder = new DbContextOptionsBuilder<MovieTheaterDBContext>();
        optionsBuilder.UseSqlServer(ConnectionString);

        return new MovieTheaterDBContext(optionsBuilder.Options);
    }

   
}

appsettings.json:

{
  "ConnectionStrings":
  {
    "MovieTheaterDBContext": "Server=DESKTOPM4\\SQLEXPRESS;Database=EshopSolution;Trusted_Connection=True;"
  }
}

Update: It is my mistake, I have not set this project as startup project .So it can't find appsettings.json.

2
  • 1
    Looks like this line .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) or variant: stackoverflow.com/a/60199695/495455 Commented Mar 12, 2021 at 1:58
  • Hi @Mistake,please share how do you call MovieTheaterDBContextFactory method? Commented Mar 12, 2021 at 6:14

2 Answers 2

0

Right click on appsettings.json file and go to the properties and change "Copy to output directory" option to "Copy always"

Sign up to request clarification or add additional context in comments.

Comments

0

Check that your appSettings.json file is in the directory where all your projects file are located. Where the .csproj is located.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.