In code first approach firstly we will write the Model and Context class then Framework will create database and required code for us.
In this demo, I m using Asp.net core 3.0 web api and In-memory database for just testing the web api concept.
Step 1 : Create the asp.net core web api project like this
Step 2: In Solution Explorer, right-click the project. Select Add > New Folder. Name the folder Models and Add the class Emp
namespace EmpApiDemo.Models { public class Emp { public long Id { get; set; } public string Name { get; set; } public string Address { get; set; } public string EmailId { get; set; } } }
Step 3:: Add the following package from Nuget for EF code first and In-Memory Database like this
In the above package Microsoft.EntityFrameworkCore.SqlServer is used for doing database operation with Sqlserver.
Microsoft.EntityFrameworkCore.InMemory: is used for creating the sql database In-Memory. This is generally useful while creating the demo for POC.
Step 4: In same model folder add the EmpContext.cs file and write the code like this
using Microsoft.EntityFrameworkCore; namespace EmpApiDemo.Models { public class EmpContext : DbContext { public EmpContext(DbContextOptions<EmpContext> options) : base(options) { } public DbSet<Emp> Emps { get; set; } } }
Step 5: Register the database context in Startup.cs file like this
Step 6: Create the Web Api Controller i.e. EmpsController using Scaffold like this
Now this will auto generate the CRUD operation web api code for us like this
using EmpApiDemo.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EmpApiDemo.Controllers { [Route("api/[controller]")] [ApiController] public class EmpsController : ControllerBase { private readonly EmpContext _context; public EmpsController(EmpContext context) { _context = context; } // GET: api/Emps [HttpGet] public async Task<ActionResult<IEnumerable<Emp>>> GetEmps() { return await _context.Emps.ToListAsync(); } // GET: api/Emps/5 [HttpGet("{id}")] public async Task<ActionResult<Emp>> GetEmp(long id) { var emp = await _context.Emps.FindAsync(id); if (emp == null) { return NotFound(); } return emp; } // PUT: api/Emps/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. [HttpPut("{id}")] public async Task<IActionResult> PutEmp(long id, Emp emp) { if (id != emp.Id) { return BadRequest(); } _context.Entry(emp).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!EmpExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Emps // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. [HttpPost] public async Task<ActionResult<Emp>> PostEmp(Emp emp) { _context.Emps.Add(emp); await _context.SaveChangesAsync(); return CreatedAtAction("GetEmp", new { id = emp.Id }, emp); } // DELETE: api/Emps/5 [HttpDelete("{id}")] public async Task<ActionResult<Emp>> DeleteEmp(long id) { var emp = await _context.Emps.FindAsync(id); if (emp == null) { return NotFound(); } _context.Emps.Remove(emp); await _context.SaveChangesAsync(); return emp; } private bool EmpExists(long id) { return _context.Emps.Any(e => e.Id == id); } } }
Step 7: Now run the application and test on post man like this
For Saving record
For Updating Record
For Deleting Record
For Fetching the Record
In this demo we saw that how to create the Web API CRUD operation using database first approach. We also saw that how to use In-memory database for creating the demo application with sql server.
is this code first or DB firts.
It is code first approach.
It is code first approach.