Create API using Code First Approach in .NET Core

Here, we will learn about how to create an API using Code First Approach in .NET Core

Step 1: Create a New ASP.NET Core Web API.

Step 2: Install the above Packages.

Step 3: Create Model class Customer.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Code_First_Approch.Model
{
    public class Customer
    {
        [Key]
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public string Address { get; set; }
        public string ZipCode { get; set; }
    }
}

Step 4: Create DemoDbContext.

using Code_First_Approch.Model;
using Microsoft.EntityFrameworkCore;

namespace Code_First_Approch
{
    public class DemoDbContext:DbContext
    {
        public DemoDbContext(DbContextOptions<DemoDbContext> options) : base(options)
        {
        }

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

Step 5: appsetting.json Add ConnectionString.

{
  "ConnectionStrings": 
  {
    "DefaultConnection": "Server=VISION-029\\SQLEXPRESS;Initial Catalog=DemoFirstApproch;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": 
  {
    "LogLevel": 
    {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Step 6: Give Command for the package console.

  • Enable-Migrations
  • Add-Migration MyMigration
  • Update-database

Step 7: If you working with API then the advantage of the Swagger.

What is Swagger?

  • A tool that can be used to provide a UI representation of your API with ease.
  • Once you have generated Swagger documentation for your API.
  • You can view the signature of your API methods and even test your API methods as well.

Implementation::

1: Install package

2: Write below code in Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Code_First_Approch
{
    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)
        {
            //swagger
            services.AddMvc();
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "Test API",
                    Description = "A simple example for swagger api information",
                    Contact = new OpenApiContact
                    {
                        Name = "Your Name XYZ",
                        Email = "xyz@gmail.com",
                        Url = new Uri("https://example.com"),
                    },                  
                });
            });

            //configconnectionstring
            services.AddControllersWithViews();
            services.AddDbContext<DemoDbContext>(item => item.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //swagger
            app.UseSwagger();
            app.UseSwaggerUI(c => {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API V1");
            });

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Step 8: Write the below code in the customer controller.

using Code_First_Approch.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Code_First_Approch.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class CustomerController : Controller
    {
        private readonly DemoDbContext _demoDbContext;

        public CustomerController(DemoDbContext demoDbContext) 
        {
            _demoDbContext = demoDbContext;
        }
      
        [HttpGet("GetAllCustomers")]
        public ActionResult GetAllCustomers() 
        {
            var customer = _demoDbContext.Customer.ToList();
            if (customer != null)
            {
                return Ok(customer);
            }
            else 
            {
                return NotFound("Data Not Found");
            }
        }

        [HttpPost("Addcustomer")]
        public ActionResult Addcustomer([FromBody]Customer  model) 
        {
            if (model != null) 
            {
                try
                {
                    Customer customer = new Customer();
                    customer.CustomerName = model.CustomerName;
                    customer.Email = model.Email;
                    customer.PhoneNumber = model.PhoneNumber;
                    customer.Address = model.Address;
                    customer.ZipCode = model.ZipCode;

                    _demoDbContext.Customer.Add(customer);
                    _demoDbContext.SaveChanges();

                    return Ok(GetAllCustomers());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            return Ok();
        }

        [HttpGet("Customer/{id}")]
        public ActionResult GetCustomerById(int id) 
        {
            var customer = _demoDbContext.Customer.FirstOrDefault(x => x.CustomerId == id);
            if (customer != null)
            {
                return Ok(customer);
            }
            else 
            {
                return NotFound();
            }
        }

        [HttpPut("UpdateCustomer")]
        public ActionResult UpdateCustomer([FromBody]Customer model) 
        {
            var customer = _demoDbContext.Customer.FirstOrDefault(x => x.CustomerId == model.CustomerId);
            try
            {
                if (customer != null)
                {
                    customer.CustomerName = model.CustomerName;
                    customer.Email = model.Email;
                    customer.PhoneNumber = model.PhoneNumber;
                    customer.Address = model.Address;
                    customer.ZipCode = model.ZipCode;

                    _demoDbContext.Customer.Update(customer);
                    _demoDbContext.SaveChanges();

                    return Ok(GetAllCustomers());
                }
                else 
                {
                    return BadRequest();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return Ok();
        }

        [HttpDelete("Customer/{id}")]
        public ActionResult DeleteCustomer(int id) 
        {
            if (id > 0)
            {
                var customer = _demoDbContext.Customer.FirstOrDefault(x => x.CustomerId == id);
                _demoDbContext.Customer.Remove(customer);
                _demoDbContext.SaveChanges();
                return Ok(GetAllCustomers());
            }
            return Ok();
        }

    }
}

Step 9: Run API and Then see below Screen.

Submit a Comment

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

Subscribe

Select Categories