Connect to the database using .Net Core 2

0

I am studying .Net Core 2 and I am not able to connect to the database.

My appsettings.json looks like this:

"ConnectionStrings": {
     "DefaultConnection": "Server=FAYOL\SQLEXPRESS;Database=Pagamento;Trusted_Connection=True;MultipleActiveResultSets=true"
},

And the Startup.cs

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Repository; 
namespace Radix
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

        var connection = @"Server=FAYOL\SQLEXPRESS;Database=Pagamento;Trusted_Connection=True;ConnectRetryCount=0";
        services.AddDbContext<Contexto>(options => options.UseSqlServer(connection));
    }
}

}

I'm not sure how to point Startup.cs to Json and how to do that. I took an example on the internet that puts the string right in ConfigureServices (like the example above) and is giving error.

Can you help me?

Thank you

    
asked by anonymous 25.05.2018 / 21:19

1 answer

0

To recover the connection string from appsettings.json you can do as follows

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration
using Microsoft.Extensions.DependencyInjection;
using Repository; 
namespace Radix
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            string connecttionStringV2 = Configuration.GetSection("ConnectionStrings")["DefaultConnection"];
            string connectionString = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<Contexto>(options => options.UseSqlServer(connection));
        }
    }
}
    
25.05.2018 / 21:25