Configuration

ASP.NET Core supports accessing configuration data from a variety of sources, like JSON files, environment variables, and command-line arguments.

Configuring a connection string in an appsetting.json file:

JSONCopy

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;"
  }
}

In the Program.cs file:

C#Copy

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

app.Run();

With the previous code:

  • The connection string is configured in the appsettings.json file.
  • The WebApplicationBuilder is used to configure the app.
  • The AddDbContext method registers the DbContext with the dependency injection container.
  • The connection string is retrieved from the configuration and used to set up the database context.
comptia certification malaysia

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *