CRUD Operations in ASP.NET Core using Entity Framework Core
In this blog you will learn how to do CRUD Operations in ASP.NET Core using Entity Framework Core using AngularJS.
Read our full blog to understand the crux of the topic better. If you want to create a >single Page App with Angular.js, Node.js and MongoDB, refer to the blog.
Create a folder named Model.
>>
Create a class name TblCustomer inside the model folder and write the property.
Make ID as the primary key and auto-generated.
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema;
namespace WebApiCoreLecture.Model { public class TblCustomer { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [StringLength(150)] public string Name { get; set; } [StringLength(150)] public string LastName { get; set; } [StringLength(250)] public string Email { get; set; } public int Age { get; set; } public string Gender { get; set; } public int IsActive { get; set; } } } |
Now, create a context class inside model folder name Customer. Inherit the class with the DbContext which is class of entity framework. Then make a constructor using dependency injection and initialise the DbContext class. Also, make a database set property of the created model class.
using Microsoft.EntityFrameworkCore; namespace WebApiCoreLecture.Model { public class CustomerContext : DbContext { public CustomerContext(DbContextOptions<CustomerContext> options) : base(options) { } public DbSet<TblCustomer> Customer { get; set; } } } |
Now, We need to create a connection string and name the database "AngularAppDb". It will create database with the name "AngularAppDb".
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "ConnectionStrings": { "ConEmp": "Server=DESKTOP-HBLN74L\\SQLEXPRESS; Database=AngularAppDb; Trusted_Connection=True;" }, "AllowedHosts": "*" } |
Now, we need to add the following line in the startup file in ConfigureServices.
services.AddDbContext<CustomerContext>(db => db.UseSqlServer(Configuration.GetConnectionString("ConEmp")));
We need to make a controller with the name Customer.
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApiCoreLecture.Model;
using WebApiCoreLecture.Model.ResponseModel;
namespace WebApiCoreLecture.Controllers { [Route("api/[controller]/[action]")] [ApiController] [EnableCors("AllowOrigin")] public class CustomerController : ControllerBase { private readonly CustomerContext _context; public CustomerController(CustomerContext context) { _context = context; }
[HttpGet] public async Task<ActionResult<IEnumerable<TblCustomer>>> TblCustomer() { ResponseModels Response = new ResponseModels();
return await _context.Customer.ToListAsync(); Response.Code = 200; Response.Message = "Showing list of customer"; }
[HttpPost] public async Task<ActionResult<TblCustomer>> PostCustomer(TblCustomer model) { ResponseModels response = new ResponseModels(); try { TblCustomer cus = new TblCustomer(); cus.Name = model.Name; cus.LastName = model.LastName; cus.Email = model.Email; cus.Age = model.Age; cus.Gender = model.Gender; _context.Customer.Add(cus); _context.SaveChanges(); response.Code = 200; response.Message = "Succesfully Inserted"; } catch (Exception e) { response.Code = 400; response.Message = "Something went wrong"; } return Ok(response); }
[HttpDelete("{Id}")] public async Task<ActionResult<TblCustomer>> DeleteCustomer(int id) { ResponseModels response = new ResponseModels(); try { var deletion = await _context.Customer.Where(x => x.Id == id).FirstOrDefaultAsync(); if(deletion!= null) { _context.Customer.Remove(deletion); _context.SaveChanges(); response.Code = 200; response.Message = "Successfully Deleted"; } else { response.Code = 400; response.Message = "Something went wrong"; } } catch (Exception e) { response.Code = 400; response.Message = "Something went wrong"; } return Ok(Response); }
[HttpPost] public async Task<ActionResult> UpdateCus(CusModel model) { ResponseModels response = new ResponseModels(); try { var updateCustomer = await _context.Customer.Where(x => x.Email == model.Email).FirstOrDefaultAsync(); if (updateCustomer == null) { response.Code = 400; response.Message = "User not found!!"; return Ok(response); }
updateCustomer.Name = model.Name; updateCustomer.LastName = model.LastName; updateCustomer.Age = model.Age; updateCustomer.Gender = model.Gender; _context.Update(updateCustomer); if (_context.SaveChanges() > 0) { response.Code = 200; response.Message = "Record Update Successfully."; }
} catch (Exception ex) { response.Code = 400; response.Message = ex.Message; } return Ok(response); } } } |
Now, we need to migrate and update the database.
Go to Tools > NuGet Package Manager > NuGet Package Console
Type the following command to migrate-
add-migration anyname
After migration, we need to update the database using the following command-
update-database
Now, open the SQL server management system, all we can see here is our created database
>>
After expanding the table of AngularAppDb, we can see the table name Customer
>>
>>
Our API is working on a different port or localhost and our Angular project is running on a different port.
We can also say it is the origin. The communication between two different ports can happen directly.
To make it happen, we need to allow it from api. So, we need to add CORS in our startup file inside ConfigureServices.
services.AddCors(o => o.AddPolicy("AllowOrigin", builder => { builder.AllowAnyHeader() .AllowAnyMethod() .SetIsOriginAllowed((host) => true) .AllowCredentials(); })); |
and also add the following line after routing in Configure method in startup file.
app.UseCors("AllowOrigin");
Suggested blogs:
>Steps to convert your Angular App to a Native Mobile
>Create a basic Web Application with Angular
>Setting up the local environment for Angular development
>Building a web application with Angular and Firebase
>How To Build Progressive Web Apps with Angular
>A complete guide on Life Cycle of Angular Component
>A complete guide to Perform crud operation in angular using modal popup