Pages

CRUD Operations In ASP.NET Core Using Entity Framework Core Code First with Angularjs

 Create a folder named Model.





Create a class name TblCustomer inside model folder and write the property.

Make Id as 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 controller with 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 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 database using following command-
update-database

Now, open the sql server management system, all we can see here our created database




 After expanding the table of AngularAppDb, we can see the table name Customer







Our Api is working on different port or localhost and our Angular project is running on different port.
We can also say it cross origin. The communication between two different port can be 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");












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...