Today, we will learn about how we can implement CRUD operation with Angular 7 in .NET Core Web API. A Web API is used to provide connectivity between a Frontend application and Database.
Firstly we will begin with Backend login
Create a new project in Visual Studio
Choose ASp.NET Core Web Application and click Ok
Choose API for .NET Core and be sure you have unchecked the HTTPS Configuration and create the project.
We are going to use the Code First Approach. So first we add the tables we are going to use.
Create a new Folder as Models and add Context.cs class in it.
using Microsoft.EntityFrameworkCore; namespace CrudOperationWithAngular7.Models { public class Context : DbContext { public Context(DbContextOptions<Context> options) : base(options) { } public DbSet<CrudTable> CrudTables { get; set; } } }
In the same folder create CrudTable.cs file
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CrudOperationWithAngular7.Models { public class CrudTable { [Key] public int Id { get; set; } [Required] [Column(TypeName = "nvarchar(100)")] public string Name { get; set; } [Required] [Column(TypeName = "nvarchar(16)")] public string PhoneNumber { get; set; } [Required] [Column(TypeName = "nvarchar(5)")] public string Age { get; set; } } }
Add the connection string in appsettings.json file
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "DevConnection": "Server=DESKTOP-CGB025P;Database=DotNetCoreDb;Trusted_Connection=True;MultipleActiveResultSets=True;" } }
Add the migration for it.
Fire the following command from the command prompt opened.
Add-Migration Initial Update-Database
Its time to create the Controller which will interact with FrontEnd and Database
Navigate to Controllers -> Add new empty controller as CrudController and replace it with the following code.
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CrudOperationWithAngular7.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace CrudOperationWithAngular7.Controllers { [Route("api/[controller]")] [ApiController] public class CrudController : ControllerBase { private readonly Context _context; public CrudController(Context context) { _context = context; } [HttpGet] public IEnumerable<CrudTable> GetCrudTables() { return _context.CrudTables; } [HttpPut("{id}")] public async Task<IActionResult> PutCrudTable([FromRoute] int id, [FromBody] CrudTable CrudTable) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != CrudTable.Id) { return BadRequest(); } _context.Entry(CrudTable).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CrudTableExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } [HttpGet("{id}")] public async Task<ActionResult<CrudTable>> GetCrudTable(int id) { var CrudTable = await _context.CrudTables.FindAsync(id); if (CrudTable == null) { return NotFound(); } return CrudTable; } [HttpPost] public async Task<IActionResult> PostCrudTable([FromBody] CrudTable CrudTable) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _context.CrudTables.Add(CrudTable); await _context.SaveChangesAsync(); return CreatedAtAction("GetCrudTable", new { id = CrudTable.Id }, CrudTable); } [HttpDelete("{id}")] public async Task<IActionResult> DeleteCrudTable([FromRoute] int id) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var CrudTable = await _context.CrudTables.FindAsync(id); if (CrudTable == null) { return NotFound(); } _context.CrudTables.Remove(CrudTable); await _context.SaveChangesAsync(); return Ok(CrudTable); } private bool CrudTableExists(int id) { return _context.CrudTables.Any(e => e.Id == id); } } }
Finally, open the StartUp.cs file and replace it with the following code
using CrudOperationWithAngular7.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json.Serialization; namespace CrudOperationWithAngular7 { 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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddJsonOptions(options => { var resolver = options.SerializerSettings.ContractResolver; if (resolver != null) (resolver as DefaultContractResolver).NamingStrategy = null; }); services.AddDbContext<Context>(options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection"))); services.AddCors(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors(options => options.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader()); app.UseMvc(); } } }
Enter the port number for your Angular Application. By default, it is 4200
Front end development for this application is continued in Part-2.
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular