Build an ASP.NET Core API Using the Existing Database

Introduction 
 
In this post, I’m going to develop an ASP.Net Core web API. Before start writing some code to develop a core web API, a question arises. Why do we need web APIs during development? Well, when we want to build a web application, Windows application or Mobile application, a web API is necessary. If we store, retrieve, manipulate and update the data in a common server and let the other applications (web applications, mobile applications, IoT devices, etc.) request and retrieve the same data from that server, these things can be easily done with web APIs by means of a commonplace web API. Therefore, it is a better practice to use a Web API to get, save or update the data with all essential business logic of your application. It will be easy to maintain the application and it will be required to make changes in only one place.
 
The journey of .NET Core started with the intent of Microsoft to build a common .NET base library that provides a common foundation to all its platforms. With this in mind, Microsoft released the first open-source version of .NET Core 1.0 on the 27 of June 2016, along with ASP.NET Core 1.0 and Entity Framework. This ASP.NET Core is a redesigned version of ASP.NET that can run on .NET Core or .NET Framework both. The developers can use ASP.NET Core to build web apps and services, IoT apps, and mobile backends. ASP.NET Core is also available on three Major platforms — Windows, Mac, and Linux.
 
Prerequisites

Getting started

 
Step 1
 
Open Visual Studio 2019 on your computer.
 
Step 2
 
Now click "Create a new Project" in Visual Studio 2019.
 
Build ASP.NET Core API Using Existing Database 
 
Step 3
 
Select "ASP.NET Core Web Application" and hit the Next Button.
 
Build ASP.NET Core API Using Existing Database 
 
Step 4
 
In the next window, fill your project details and location, then click the Create Button.
 
Build ASP.NET Core API Using Existing Database
 
Step 5
 
Here, the API Template Selection UI shows up. Before selecting, you should have a look at two dropdowns on top (You can select any of Core version 3.0 or 3.1). Make sure those are filled accordingly below the image. Now select the API as your project type and click the Create Button.
 
Build ASP.NET Core API Using Existing Database
 
Step 6
 
After some loading, this project loads and you can see in the solution explorer of your Visual Studio with proper project structure. You can build, run and test the project.
 
Build ASP.NET Core API Using Existing Database
 
Step 7
 
If it all looks good, its time to introduce the EF core in the project. We are using the EF core database first approach in this post. So, you have an existing database, using the Scaffold-DbContext command you can generate entity and context classes based on the schema of the existing database. For this, go step by step.
  1. Open the Package Manager Console(From the View menu, select Other Windows > Package Manager console. )
  2. Install the NuGet package below one-by-one.
Build ASP.NET Core API Using Existing Database
  1. Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.0.0 
Build ASP.NET Core API Using Existing Database
  1. Install-Package Microsoft.EntityFrameworkCore.Design -Version 3.0.0  
Build ASP.NET Core API Using Existing Database
  1. Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.0.0  
Now it's time to generate entity and context classes, run the following command in Package Manager console.(Replace your connection string as Well)
 
Scaffold-DbContext "YourConnectionString" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context CoreDbContext -DataAnnotations
 
Build ASP.NET Core API Using Existing Database
 
Scaffold-DbContext "Server=.;Database=CoreApi;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context CoreDbContext -DataAnnotations
 
Step 8
 
Now time to add the Connection string to your appsettings.json. Add the below lines to appsettings.json.
  1. "ConnectionStrings": {  
  2.    "Database""YourConnectionString"  
  3. },   
  1. {    
  2.   "Logging": {    
  3.     "LogLevel": {    
  4.       "Default""Information",    
  5.       "Microsoft""Warning",    
  6.       "Microsoft.Hosting.Lifetime""Information"    
  7.     }    
  8.   },    
  9.   "ConnectionStrings": {    
  10.     "Database""Server=(local);Database=CoreApi;Trusted_Connection=True;"    
  11.   },    
  12.     
  13.   "AllowedHosts""*"    
  14. }   
Step 9
 
It's time to add the DbContext at your Startup.cs. Add the below lines to Startup.cs.
  1. services.AddDbContext<CoreDbContext>(op => op.UseSqlServer(Configuration.GetConnectionString("Database")));  
  1. public class Startup  
  2.    {  
  3.        public Startup(IConfiguration configuration)  
  4.        {  
  5.            Configuration = configuration;  
  6.        }  
  7.   
  8.        public IConfiguration Configuration { get; }  
  9.   
  10.        // This method gets called by the runtime. Use this method to add services to the container.  
  11.        public void ConfigureServices(IServiceCollection services)  
  12.        {  
  13.            services.AddDbContext<CoreDbContext>(op => op.UseSqlServer(Configuration.GetConnectionString("Database"))); //Add   
  14.            services.AddControllers();  
  15.        }  
  16.   
  17.        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  18.        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  19.        {  
  20.            if (env.IsDevelopment())  
  21.            {  
  22.                app.UseDeveloperExceptionPage();  
  23.            }  
  24.            app.UseHttpsRedirection();  
  25.            app.UseRouting();  
  26.            app.UseAuthorization();  
  27.            app.UseEndpoints(endpoints =>  
  28.            {  
  29.                endpoints.MapControllers();  
  30.            });  
  31.        }  
  32.    }  
Step 10
 
Now your web API is ready to build and run.
 
Build ASP.NET Core API Using Existing Database
 

Summary

In this article, I created a new core web API project as a test project. While there's nothing much in this example, it is very basic and a prefect initial point to creating an awesome API. For a better understanding of this project, you can visit this git repository. In my next post, I will show the implementation of Swagger documentation in the same API Project. If you like this article, feel free to share it with your friends.