Build ASP.NET Core API Using Existing Database

In this post, I’m going to develop an ASP.Net Core web API. Before writing some code to develop a core web API, A question comes into existence. Why do we need those web APIs during development? When we want to build an application for a Web or Windows or Mobile platform, a web API is necessary. The reason is if we want to store, retrieve, manipulate and update the data in a common server and let the other application (web application, mobile application, IoT devices, etc.) request and retrieve the same data from that server if needed. This stuff can be done easily by web APIs by having a web Api at Commonplace. So it is always a best practice to have a WebAPI with all essential business logic of your application so that we can perform all CRUD operations threw the web API. It will become easy to maintain as  the application will only need to make changes in one place.
 
Now to get to  the topic, here I’m sharing a short overview of Asp.NET Core. The journey of DotNET Core starts with the purpose of Microsoft to build a common base library to provides a common foundation for all Microsoft platforms. With this thought, Microsoft had released the first open-source version of .NET Core 1.0 on 27 June 2016, along with ASP.NET Core 1.0 and Entity Framework. This newly introduced 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
  • You need to have Dotnet core 3.1 or 3.0 versions in your machine.
  • Visual Studio 2019
  • An existing SQL Server Database.
Step 1
 
Open Visual Studio 2019 on your computer.
 
Step 2
 
Now click at "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 Next Button.
 
Build ASP.NET Core API Using Existing Database
 
Step 4
 
In the next window, fill your project details and location. Then click at Create Button.
 
Build ASP.NET Core API Using Existing Database
 
Step 5
 
The API Template Selection UI shows up. Before selection, 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 Create Button.
 
Build ASP.NET Core API Using Existing Database
 
Step 6
 
The newly created project loads in visual studio. You will see the project in the solution explorer. You can run and test the project.
 
Build ASP.NET Core API Using Existing Database
 
Step 7
 
If everything looks good, its time to introduce the EF core in the project. We are using EF core database first approach in this post. 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 the same go step by step.
  1. Open Package Manager Console(From the View menu, select Other Windows > Package Manager console. )
  2. Install below the NuGet package one by one.
  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    
Build ASP.NET Core API Using Existing Database
 
Step 8
 
Now it's  time to generate entity and context classes, run following command in Package Manager console (Replace your connection string as well).
  1. Scaffold-DbContext "Server=.;Database=CoreApi;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context CoreDbContext -DataAnnotations  
Build ASP.NET Core API Using Existing Database
 
Step 9
 
Now it's  time to add the Connection string at your appsettings file. Add the below lines to appsettings.json.
  1. "ConnectionStrings": {      
  2.    "Database""YourConnectionString"      
  3. },     
Your app settings JSON file should be or maybe similar to the below Snippet.
  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 10
 
Now it's  time add the DbContext at your Startup file. Add the below lines to Startup.cs.
  1. services.AddDbContext<CoreDbContext>(op => op.UseSqlServer(Configuration.GetConnectionString("Database")));     
Your Startup Class should be similar to the below Snippet.
  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 11
 
Now, your web API is ready to build and run. 
 
Build ASP.NET Core API Using Existing Database
 

Closing

 
In this article, I built a new core web API project as a test project. This exzmple is very basic and a perfect initial point to creating an awesome API. You can visit this git repository for a better understanding of this project. I will let you know the implementation of Swagger documentation in the same API Project in my next post. If you like this article, feel free to share it with your friends.