Section12: EnsureCreated method (Restful API in ASP .Net Core)

 Section12: EnsureCreated method


Introduction:


In previous sections, we have seen how we create Model (represents a table in the DB), Controller (receives data from the server and add it to the DB). We also added an AppDBConext which takes care of database operations. We have also registered this AppDBContext to the service in Section 11.


What is EnsureCreated?

We have done all setup required to perform the CRUD (Create, Read, Update and Delete) operations on our DB. But to create a DB in SQL server, we have to use Migrations (discussed later). Migrations are useful when there is a change in the model. For instance, if we add a new field to the table (model), then we have to change the model and update the table using migrations.

If we are sure that we don't change the model later, then we can use EnsureCreated() method.

This method will create a DB in the SQL server if not already created.


In ASP .Net Core 6, since we don't have startup.cs, there is a change in a way we use EnsureCreated method in .Net 6. 

After adding this method to the service, we shall create a new controller and inject the AppDBConect into this controller. The reason we inject this is that the controller should be able to access the DB. And we can access our DB using AppDBConext.


To add EnsureCreated Method, add below code in program.cs file as shown in the below video

var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDBContext>();
db.Database.EnsureCreated();