Understanding ASP.Net Core 2.2 Database Context Class


When working in asp.net core 2.2, you will come across the class in the Model folder called DatabaseContext or with another name depending on how you named it when you scaffolded your models from tables in the database.

This Context class contains logic for your tables in the database, depending on if you use Database First or Code First methodology:

- Code First is when you create a DatabaseContext without having Database Tables present in the Database. All the table designs are done in the DatabaseContext class then create a migration and update the database to create tables designed in Database Context.

In a Database First methodology, Software Developers create/generate Models and the Database Context from the tables that are already created in the database. It doesn't matter which methodology you use, some developers choose to craft their tables and their relationships in the code-first, some desire to start with the database then scaffold their models from there. 

For example:

 private void ConfigureTableName(EntityTypeBuilder<TableName> builder){
builder.ToTable("TableName");
builder.Property(c => c.Id)
.ForSqlServerUseSequenceHiLo("TableName_hilo") //Research about TableName_hilo
.IsRequired(true);
}
</code>
</pre>

When creating a Code First Database Context, you define what the table is going to require. This is just the same as designing the database tables.

The ForSqlServerUseSequenceHiLo means that the Id which is a primary key that will be created in the database table will have a high-low portion.
- For every high number, there will be low numbers from 0 to 100 when all low numbers are exhausted a new high number is assigned from the memory.

- When you migrate the Code First to the database you will see the sequence number with a column name of TableName_hilo

The Database Context is supposed to have ta DBSet attribute that registers the tables created herein, without this attribute, you won't be able to insert or even get the tables data from the database, this is important.

Remember to register the Database context as a service in the Start-Up class in the ASP.Net Core 2.2 for you to be able to inject the database context in the whole application:

- When I say, inject the DatabaseContext, I mean that, for the DabaseContext class to be available to other classes on Run Time, it has to be registered in the StartUP class. This is the greatest thing that has ever happened in DotNet Core, dependency injection.

 

 







For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email AddressContact: [email protected]