Thursday, 15 August 2019

CRUD operations using CORE MVC(2.1) ,Repository Pattern & Dependency Injection

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

namespace WebApplication2.Models
{
    public class EMP
    {
        [Key]
        public int EID { get; set; }
        public string NAME { get; set; }
    }
}

View Model:

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

namespace WebApplication2.Models
{
    public class EMPVM
    {
        [Required(ErrorMessage ="Eid should not be blank.")]
        public int EID { get; set; }
        [Required(ErrorMessage = "Name should not be blank.")]
        public string NAME { get; set; }
    }
}

Repository :

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

namespace WebApplication2.Models
{
   public interface IRepository
    {
        IEnumerable<EMP> Gets();
        EMP Get(int EID);
        EMP Save(EMP emp);
        EMP Update(EMP emp);
        EMP Delete(int EID);
    }
}

Implement Repository :

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

namespace WebApplication2.Models
{
    public class SQLRepository : IRepository
    {
        private readonly AppDbContext context;
        public SQLRepository(AppDbContext Context)
        {
            this.context = Context;
        }
        

        public EMP Get(int EID)
        {
            return context.EMPs.Find(EID);
        }

        public IEnumerable<EMP> Gets()
        {
            return context.EMPs;
        }

        public EMP Save(EMP emp)
        {
            context.EMPs.Add(emp);
            context.SaveChanges();
            return emp;
        }

        public EMP Update(EMP emp)
        {
            var Emp = context.EMPs.Attach(emp);
            Emp.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            context.SaveChanges();
            return emp;
        }
        public EMP Delete(int EID)
        {
            EMP emp = context.EMPs.Find(EID);
            if (emp != null)
            {
                context.EMPs.Remove(emp);
                context.SaveChanges();
            }
            return emp;
        }
    }
}
DbContext :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace WebApplication2.Models
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options):base(options)
        { }
        public DbSet<EMP> EMPs { get; set; }
    }
}
    
Add connection string in appsettings.json :

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DBConnection": "server=(localdb)\\MSSQLLocalDB;database=sivdb;Trusted_Connection=true"
  }
}

Register Dependency Injection in dependency  container Startup.cs:

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

namespace WebApplication2
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DBConnection")));
            services.AddScoped<IRepository, SQLRepository>();
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Test}/{action=Index}/{id?}");
            });
        }
    }
}
Use 2 commands for migration :
Add-Migration Intialmigraion
Update-Database

Controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class TestController : Controller
    {
        private IRepository _iRepository;
        public TestController(IRepository iRepository)
        {
            this._iRepository = iRepository;
        }
        [HttpGet]
        public IActionResult Index()
        {
            return View(_iRepository.Gets());
        }
        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(EMPVM vm)
        {
            if (ModelState.IsValid)
            {
                EMP emp = new EMP();
                emp.NAME = vm.NAME;
                EMP emp1=_iRepository.Save(emp);
                return RedirectToAction("Index");
            }
            return View(vm);
        }
        [HttpGet]
        public IActionResult Edit(int id)
        {
            EMP emp = _iRepository.Get(id);
            EMPVM vm = new EMPVM();
            vm.EID = emp.EID;
            vm.NAME = emp.NAME;
            return View(vm);
        }
        [HttpPost]
        public IActionResult Edit(EMPVM vm)
        {
            if (ModelState.IsValid)
            {
                EMP emp = new EMP();
                emp.EID = vm.EID;
                emp.NAME = vm.NAME;
                EMP empn = _iRepository.Update(emp);
                return RedirectToAction("Index");
            }
            return View(vm);
        }
        [HttpGet]
        public IActionResult Delete(int id)
        {
            EMP emp = _iRepository.Delete(id);
            return RedirectToAction("index");
        }
    }
}
Index view :

@model IEnumerable<EMP>

@{
    ViewData["Title"] = "Index";
}



<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table table-bordered table-hover table-responsive-lg table-striped">
    <thead class="bg bg-primary">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.EID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.NAME)
            </th>
            <th>ACTION</th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.NAME)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new {  id=item.EID}) |
                @Html.ActionLink("Delete", "Delete", new {  id=item.EID })
            </td>
        </tr>
}
    </tbody>
</table>

Create View :

@model WebApplication2.Models.EMPVM

@{
    ViewData["Title"] = "Create";
}


<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="EID" class="control-label"></label>
                <input asp-for="EID" class="form-control" />
                <span asp-validation-for="EID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="NAME" class="control-label"></label>
                <input asp-for="NAME" class="form-control" />
                <span asp-validation-for="NAME" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Edit View :

@model WebApplication2.Models.EMPVM

@{
    ViewData["Title"] = "Edit";
}


<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="EID" class="control-label"></label>
                <input asp-for="EID" class="form-control" />
                <span asp-validation-for="EID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="NAME" class="control-label"></label>
                <input asp-for="NAME" class="form-control" />
                <span asp-validation-for="NAME" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}


No comments:

Post a Comment