Today, we’re going to learn how to perform CRUD operations using Entity Framework Core in an ASP.NET Core application. We'll use a simple example with a CountryMaster table to demonstrate how to insert, retrieve, update, and delete data efficiently.

Step 1 : First we create a CountryMaster Table with Column CountryId,CountryName,CountryCode
    CREATE TABLE [dbo].[CountryMaster](
        [CountryId] [int] IDENTITY(1,1) NOT NULL,
        [CountryName] [varchar](20) NULL,
        [CountryCode] [varchar](10) NULL,
    CONSTRAINT [Pk_CountryMaster_CountryId] PRIMARY KEY CLUSTERED
    )

Step 2 : Now Add a project in visual studio 2022 (as using 2022)
Now Write your project name and location where you want to save your project.

Step 3 : Now add connect your database with application 
 Go to View >>Server Explorer 
Now click on highlighted section (Connect to Database option)

Now you will see this type of window 

Open the SQL Server and Copy the Server name as give below : 
as I am using local server  so Authentication will be Windows(if you use SQL server Authentication then fill login and password) 


Now paste the copied Server name to the Add connection window in Visual Studio :
and tick the Trust Server Certificate option and choose the database name as listed after the established the connection 



Now need the connection string  :
Go to View >> Server Explorer >> and right click on your database name as below given in snippet


you will see Properties : Then copy the connection string  :

Step 4 : Now add the copied the connection string to appsettings.json file 

 Note : - Before starting other things Just add below package for working with Entity
  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer
Step 5 : Now add a model folder to your project  and add a class with name which your table name (my table is CountryMaster)

    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    namespace EntityAPI.Model
    {
        public class CountryMaster
        {
            [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int CountryId { get; set; }
            public string CountryName { get; set; } = string.Empty;
            public string CountryCode { get; set; }=string.Empty;
           
        }
    }


Step 6 : Now add another class with for communicating your app with dataBase  (like Insert data , Update data, fetch data  and delete data )
    using Microsoft.EntityFrameworkCore;
    namespace EntityAPI.Model
    {
        public class TestAppDbContext : DbContext
        {
            public TestAppDbContext(DbContextOptions<TestAppDbContext> options) : base(options)
            {

            }
            public DbSet<CountryMaster> CountryMaster { get; set; }
        }
    }


Step 7 : Now need to establish connection app with database , as add the below line in program.cs file 

        using EntityAPI.Model;
    using Microsoft.EntityFrameworkCore;

    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.

    builder.Services.AddControllers();
    builder.Services.AddDbContext<TestAppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DbString"))); // dbstring
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.UseHttpsRedirection();

    app.UseAuthorization();

    app.MapControllers();

    app.Run();


Step 8 : Now Inject the constructor of TestAppDbContext to the controller 
and add below method for GetCountry,SetCountry,UpdateCountry and Delete country 
using EntityAPI.Model;
using Microsoft.AspNetCore.Mvc;

namespace EntityAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        private readonly TestAppDbContext _dbContext;
        public HomeController(TestAppDbContext dbContext) // inject constructor
        {
            _dbContext = dbContext;
        }
        [HttpGet("GetCountry")]
        public IList<CountryMaster> GetCountry()
        {
            return _dbContext.CountryMaster.ToList();
        }
        [HttpPost("SetCountry")]
        public IActionResult SetCountry(CountryMaster Request)
        {
            _dbContext.CountryMaster.Add(Request);
            _dbContext.SaveChanges();
            return Ok(new { message = "data saved successfully" });
        }
        [HttpPut("UpdateCountry")]
        public IActionResult UpdateCountry(CountryMaster Request)
        {
            var record = _dbContext.CountryMaster.FirstOrDefault(n => n.CountryId == Request.CountryId);
            if (record is not null)
            {
                record.CountryCode = Request.CountryCode;
                record.CountryName = Request.CountryName;
                _dbContext.SaveChanges();
            }
            return Ok(new { message = "data updated successfully" });
        }
        [HttpDelete("DeleteCountry")]
        public IActionResult DeleteCountry(CountryMaster Request)
        {
            var record = _dbContext.CountryMaster.FirstOrDefault(n => n.CountryId == Request.CountryId);
            if (record is not null)
            {
                _dbContext.CountryMaster.Remove(record);
                _dbContext.SaveChanges();
                return Ok(new { message = "data deleted successfully" });
            }
            return Ok(new { message = "Request not comepleted. try again" });
        }
    }
}


Now app is ready :
when run the application then it will looks like this :

I hope you’ve now understood how to create an API in ASP.NET Core using Entity Framework. If you found this post helpful or have any thoughts, feel free to share your feedback in the comments section below!

Leave a Reply

Your email address will not be published. Required fields are marked *


Talk to us?

Post your blog

F.A.Q

Frequently Asked Questions