.Net 6 – How to make sure Database created in Entity Framework Core .Net 6?

We can easily create the database using Entity Framework Core DbContext  in .Net 6 application. To create the database from code, we need to add below code in Program.cs.

var builder = WebApplication.CreateBuilder(args);

 

// Add services to the container.

builder.Services.AddControllersWithViews();

 

var dbConnextionString = builder.Configuration.GetConnectionString("DBConnectionString");

builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(dbConnextionString));

 

var app = builder.Build();

using (var scope = app.Services.CreateScope())

{

    var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();

 

   dbContext.Database.EnsureCreated();

}

Here  AppDbContext is the applicatiom DbContext class where we have all classes corresponding to the database tables. The database will get created with the name mentioned in the DBConnectionString which we passes to AppDbContext.

tags:

share: