Home > front end >  Configuring EF in ASP.NET Core 6 Program.cs
Configuring EF in ASP.NET Core 6 Program.cs

Time:03-09

I'm asked to make an ASP.NET Core 6 webAPI, I have no prior experience with Microsoft stuff, I'm following MS Docs Here In the Docs they teach how to configure EF in a Startup.cs file with a Main method(they forgot to update the docs ?), which is not there in an ASP.NET Core 6, My Program.cs Doesn't have a Main method and looks like this:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

How to add the EF to Program.cs in this case ?

EDIT: and how to add the CreateDbIfNotExist() (Docs) method while there is no class for it to reside in ?

CodePudding user response:

@D M comment answered my question.

CodePudding user response:

this is the code in asp.net core 6:


// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<"YOUR_DBCONTEXT">(option =>
    option.UseSqlServer(builder.Configuration.GetConnectionString(CONNECTION_STRING)));

change YOUR_DBCONTEXT and CONNECTION_STRING with your data.

  • Related