Pages

Build ASP.NET Core App with Angular: Part 2

 In the first part of our blog, we discussed the basics of building an ASP.Net Core app with Angular. Here we will learn to create our API user entity. This is the second part which will help you build an app with asp net core and angular from scratch. 


So without further delay, let’s straight away get to the topic and build an ASP.Net Core application with Angular. Follow the following steps to add an API user entity without much hustle. This ASP.Net Core app development with Angular tutorial will help you build an interactive application. 

Step 1: Create a folder

First, create a folder called ‘Entities’ and then a class called AppUser.cs.

Note: First use the keyword and then Tab, this will help you create a property. 

                                                     Source: khemlall-mangal.medium.com

Step 2: Install Entity Framework

Entity Framework is an object rational Mapper (ORM). It helps to translate the code into SQL commands that help us to update our tables in the database. 


To install, Entity Framework, visit your extension and install nuget gallery.

                                                     Source: khemlall-mangal.medium.com

Press keys Ctrl+Shift+P


Search for the nuget option and click on the nuget gallery and search for the Microsoft entity framework core. We also use SQL Lite as our database which will be changed at the time of deployment. 


Install the version that you have already installed in your project (sdk) ad. Verify the api.csproj and press on the ‘Install’ option. 

Step 3: Create DBCONTEXT class

This class will help us bridge the gap between the data and code that have access to the database along with the DBcontext class. For the ASP.Net app creation, this class is must.  


Create a new folder named Data

Create a new class called DataContext.cs

                                           Source: khemlall-mangal.medium.com

Enter the following code.


using System;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using API.Entities;

using Microsoft.EntityFrameworkCore;

namespace API.Data

{

   public class DataContext : DbContext

   {

       public DataContext(DbContextOptions options) : base(options)

       {

       }

public DbSet<AppUser> Users { get; set; }

   }

}



In the startup class under configure services add:


services.AddDbContext<DataContext>(options =>

           {

              options.UseSqlite("connection string"); (place holder for now)

           });


                                               Source: khemlall-mangal.medium.com

Step 5: Create Connection String

Go to the appsetting development.json file and copy the following code to create a Connection String.

                                                   Source: khemlall-mangal.medium.com


Again navigate back to the startup class and change a little bit of the code as we have mentioned below. 


public class Startup

   {

      private readonly IConfiguration _config;

       public Startup(IConfiguration config)

       {

           _config = config;

          

       }

// 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<DataContext>(options =>

           {

              options.UseSqlite("connection string");

           });

           services.AddControllers();

           services.AddSwaggerGen(c =>

           {

               c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });

           });

       }

// 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.UseSwagger();

               app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));

           }

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>

           {

               endpoints.MapControllers();

           });

       }

   }

}



After updating the startup class, its time to update the hardcore string that we need to add to connect string. The below code example will help you understand. 

                                                        Source: khemlall-mangal.medium.com

Code to update the hardcore string.


options.UseSqlite(_config.GetConnectionString("DefaultConnection"));

Step 6: Install a Dot Net-ef version 5.0.0

Alright, now we need to install a tool that is based on the SDK version you installed. i installed 5.0.0. 


Install the Dot Net tool for app development which is global dotnet-ef- version 5.0.0. Navigate to nugetgaller.org and search for the donet-ef tool for the same version you have. 

Step 7: Create database migration

Now that you have installed the 5.0.0 version, it's time to create a database schema or you can also code to create a database on our written code to make it simpler for you. 


Press Ctrl+Shift+P and start your nuget gallery and search for Microsoft.EntityFrameworkCore. Install the package for great design. 

                                           Source: khemlall-mangal.medium.com


Now, stop your project in case it is running and pass the following command. ASP.Net uses C# language to build a strong backend for web applications. 


dotnet ef migrations add InitialCreate -o Data/Migrations


Once you successfully run the command you must see the following folder.


                                       Source: khemlall-mangal.medium.com

Step 8: Create the Database

Run the below command to create a database.


dotnet ef database update

 

Next, install SQL Lite


Press Ctrl+Shift+P to open the database and choose the database that you just created.  


Now in order to create data you must see SQL Lite explorer and add it to your IDE.

                            Source: khemlall-mangal.medium.com


Right-click on the ‘user’ option, then New query insert and enter a few records. Below is an example that you can follow.


-- SQLite

INSERT INTO Users (Id, UserName)

VALUES (1, "RMANGAL");



Once you have successfully created and right-clicked, you should see the following table with new records. 

                                              Source: khemlall-mangal.medium.com

Step 9: Create a controller

Create a controller named UserController. We also need to create a get request in order to get all the user data and receive a specific ID. The following code will help you understand better. 


using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using API.Data;

using API.Entities;

using Microsoft.AspNetCore.Mvc;

namespace API.Controllers

{

   [ApiController]

   [Route("api/[controller]")]

   public class UsersController : ControllerBase

   {

       private readonly DataContext _context;

       public UsersController(DataContext context)

       {

           _context = context;

       }

[HttpGet]

       public ActionResult<IEnumerable<AppUser>> GetUsers()

       {

           var users = _context.Users.ToList();

           return users;

       }

[HttpGet("{id}")]

       public ActionResult<AppUser> GetUser(int id)

       {

            return _context.Users.Find(id);

         

       }

   }

}




Navigate to swagger to see the new API. 


Next, create a Collection, and after that add our getUsers request in order to verify the response. 

                                         Source: khemlall-mangal.medium.com


Send your request to https://localhost:5001/api/users and the newly added data to your database should now be visible.


Make our code asynchronous by doing so now. Making it more scalable by allowing multiple threads to operate on each request. Make your database call asynchronous if you must.

 

Code

[HttpGet]

       public async Task< ActionResult<IEnumerable<AppUser>>> GetUsers()

       {

           return await _context.Users.ToListAsync();

       }

[HttpGet("{id}")]

public async Task<ActionResult<AppUser>> GetUser(int id)

{

return await _context.Users.FindAsync(id)

}



Save your code. 


Follow the steps wise of this ASP.Net core angular sample project and create your own app. 



  




No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...