(C# ASP.NET Core) Getting Started with Database Connectivity

Here is a to-the-point tutorial on how database connectivity works in ASP.NET Core. A 3-step roadmap is laid for running your first query to a database of your choice. The tutorial concludes with an example walkthrough on adding nuget packages for a sqlite database. The actual database connectivity is done in later tutorials.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

How does it work in ASP.NET Core?

There is ONE and ONLY ONE COMMON gateway of communication with databases, and it is called the Entity Framework Core. The application code remains the same irrespective of the backend database you use. It's of the sort "write once, use with any database". For example, during development you can use a file based database, such as Sqlite, whereas in production you can attach a SQL Server, without changing your application code.

How is a common socket possible? The answer is that the Entity Framework Core sits between your application and the database. Every database provider is required to provide an implementation of the EF Core classes, for example, through nuget packages. Your application plugs into that common EF Core interface. You can replace the (EF Core + Database) socket without altering any code on your side. This is like, for example, it doesn't matter which electric company provides electricity to your home.

Which databases are supported?

At present SQL Server, Sqlite, Cosmos, PostgresSQL, MySql, Firebird, MS Access, and many more are available for connectivity through Entity Framework Core.

The complete list can be seen here - https://docs.microsoft.com/en-us/ef/core/providers/

Video Explanation with a Working Example

Please watch the following youtube video:

How is the basic Setup done?
(see the linked video for a walkthrough)

First Step: Decide your model classes and inherit a class from DbContext to write your DAL (data access layer).

Second Step: Find the nuget package of the database of your choice and add it to your project. The nuget packages can be found on the MSDN page cited above.

Third Step: Add connection string through the ConfigureServices method of your Startup.cs file - and you are ready to go!

The actual connectivity code will be explained in later chapters.

Example of adding a Sqlite Nuget Package
(see the linked video for a walkthrough)

First visit the nuget page for sqlite https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite

Locate the code for your package manager: Install-Package Microsoft.EntityFrameworkCore.Sqlite -Version x

Come to visual studio and go to the menu Tools > "Nuget Package Manager" > "Package Manager Console" and open the PM prompt. Paste your code and hit enter. Let the installation complete.


This Blog Post/Article "(C# ASP.NET Core) Getting Started with Database Connectivity" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.