I have setup an ASP.NET Core project, and configured the DbContext in Startup.cs like -
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DBContext>(options =>
options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
}
I can access the DbContext object in controller classes with dependency injection. But I need a reference of the DbContext in the Program class (in Program.cs file).
I tried the following approach, but it indicates syntax error -
public class Program
{
public static void Main(string[] args)
{
using (var db = new DBContext()) // getting syntax error here
{
db.Database.EnsureCreated();
}
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseUrls("http://localhost:4000");
});
}
So, how to get access to the DbContext object in the Program class?