Database integration with entity framework core
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 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 provide a common foundation for all Microsoft platforms. With this thought, Microsoft 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.
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 on your machine.
- Visual Studio 2019
- An existing SQL Server Database.
Step 1. Open Visual Studio 2019 on your computer.
Step 2. Now click on "Create a new Project" in Visual Studio 2019.
Step 3. Select "ASP.NET Core Web Application" and hit the Next Button.
Step 4. In the next window, fill in your project details and location. Then click on the Create Button.
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.
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.
Step 7. If everything looks good, it's time to introduce the EF core in the project. We are using the 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.
- Open Package Manager Console(From the View menu, select Other Windows > Package Manager console. )
- Install below the NuGet package one by one.
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.0.0
Install-Package Microsoft.EntityFrameworkCore.Design -Version 3.0.0
Install-Package Microsoft.EntityFrameworkCore.Design -Version 3.0.0
Step 8. Now it's time to generate entity and context classes, run the following command in the Package Manager console (Replace your connection string as well).
Scaffold-DbContext "Server=.;Database=CoreApi;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context CoreDbContext -DataAnnotations
Step 9. Now it's time to add the Connection string to your app settings file. Add the below lines to appsettings.json.
"ConnectionStrings": {
"Database": "YourConnectionString"
}
Your app settings JSON file should be or maybe similar to the below Snippet.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"Database": "Server=(local);Database=CoreApi;Trusted_Connection=True;"
},
"AllowedHosts": "*"
}
Step 10. Now it's time to add the DbContext to your Startup file. Add the below lines to Startup. cs.
services.AddDbContext<CoreDbContext>(op => op.UseSqlServer(Configuration.GetConnectionString("Database")));
Your Startup Class should be similar to the below Snippet:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CoreDbContext>(op => op.UseSqlServer(Configuration.GetConnectionString("Database"))); //Add
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Step 11. Now, your web API is ready to build and run.
Closing
In this article, I built a new core web API project as a test project. This example 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 about 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.