Creating Web API in Asp.net Core 3.0 using Code First Approach and In-Memory Database


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.

Database first approach using EF in asp.net core 3.0


In database first approach firstly we will create the database, on basis of database schema,CodeGeneration tool will create model class in application. This is one of the easy approach for doing CRUD operation in asp.net core.

Step 1:Create the database table like this

CREATE TABLE [dbo].[tblEmp](
[Id] [int] IDENTITY(1,1) NOT NULL,
[EmpName] [nvarchar](50) NULL,
[EmpAddress] [nvarchar](50) NULL,
[ContactNum] [nvarchar](50) NULL,
CONSTRAINT [PK_tblEmp] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Step 2: Create the asp.net core 3.0 application using Visual studio 2019 like this

Step 3: Install the required NuGet packages like this

in the above package Microsoft.VisualStudio.Web.CodeGeneration.Design is used for generating controllers and views.

Microsoft.EntityFrameworkCore.Tools is used for creating database context and a model class from the database.

Microsoft.EntityFrameworkCore.SqlServer is used for communicating the sql server database using Entity-framework.

Asp.net core also support scaffolding which use t4 templates to generate the code for common functionalities like insert, update, fetch and delete.

Step 4: Run the scaffold command in Package Manager Console to reverse engineer the database to create database context and entity POCO classes from tables. The scaffold command will create POCO class only for the tables that have a primary key.

Scaffold-DbContext “Server=localhost;Database=Inventory;Integrated Security=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

if we have to run this command on database update scenario then we can run like this

Scaffold-DbContext “Server=localhost;Database=Inventory;Integrated Security=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force

this command will create the model like this

Step 5: Go to the context class and remove the connection string from that file and move in appsettings.json file like this

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "InventoryDatabase": "Server=localhost;Database=Inventory;Integrated Security=True"
  }
}

Step 6: Go to controller folder and create Emp controller like given below image

Step 7: Now scaffolding will create the all the required code in EmpController and view for crud operation in view folder like this

Step 8: Now run the application, you will see the CRUD functionality for Emp. in the above demo, we have created the CRUD operation without writing the single line of code.