Friday 16 August 2019

CRUD operations using CORE MVC(2.1) ,Repository Pattern & Dependency Injection,EF code first approach



Models :

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

namespace WebApplication1.Models
{
    public class EMP
    {
        [Key]
        public int EID { get; set; }
        [MaxLength(50)]
        public string NAME { get; set; }
        public string ADDRESS { get; set; }
        [MaxLength(50)]
        public string PASSWORD { get; set; }
        [MaxLength(50)]
        public string GENDER { get; set; }
        public int CID { get; set; }
        public int SID { get; set; }

    }
}

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

namespace WebApplication1.Models
{
    public class COUNTRY
    {
        [Key]
        public int CID { get; set; }
        [MaxLength(50)]
        public string CNAME { get; set; }
    }
}

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

namespace WebApplication1.Models
{
    public class STATE
    {
        [Key]
        public int SID { get; set; }
        [MaxLength(50)]
        public string SNAME { get; set; }
        public int CID { get; set; }
    }
}


app

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

namespace WebApplication1.Models
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options):base(options)
        { }
        public DbSet<EMP> EMPs { get; set; }
        public DbSet<COUNTRY> COUNTRIEs { get; set; }
        public DbSet<STATE> STATEs { get; set; }
    }
}


IRepository Interface :

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


namespace WebApplication1.Models
{
    public interface IRepository <T> where T : class
    {
        IQueryable<T> Gets();
        Task<T> Get(int t);
        Task Save(T t);
        Task Update(T t);
        Task Delete(int t);
    }
}

Repository Class where implement the IRepository interface :

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

namespace WebApplication1.Models
{
    public class Repository<T> : IRepository<T> where T : class
    {
        private readonly AppDbContext context;
        

        public Repository(AppDbContext Context)
        {
            this.context = Context;
        }

        public async Task Delete(int t)
        {
            var data = await Get(t);
            context.Set<T>().Remove(data);
            await context.SaveChangesAsync();
        }

        public async Task<T> Get(int t)
        {
            return await context.Set<T>().FindAsync(t);
        }

        public IQueryable<T> Gets()
        {
            return context.Set<T>().AsNoTracking();
        }

        public async Task Save(T t)
        {
            await context.Set<T>().AddAsync(t);
            await context.SaveChangesAsync();
        }

        public async Task Update(T t)
        {
            context.Set<T>().Update(t);
            await context.SaveChangesAsync();
        }

       
    }
}

Connection string in the appsettings.json file :

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

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.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApplication1.Models;

namespace WebApplication1
{
    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_1);
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DBConnection")));
            services.AddScoped<IRepository<EMP>, Repository<EMP>>();
            services.AddScoped<IRepository<COUNTRY>, Repository<COUNTRY>>();
            services.AddScoped<IRepository<STATE>, Repository<STATE>>();

        }

        // 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");
                app.UseHsts();
            }

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

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Test}/{action=Index}/{id?}");
            });
        }
    }
}

View Model :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Immutable;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace WebApplication1.Models
{
    public class EMPVM
    {
        public EMPVM()
        {
            LCID = new List<SelectListItem>();
            LSID = new List<SelectListItem>();
        }
        public int EID { get; set; }
        [Required(ErrorMessage ="Name should not be blank.")]
        [MaxLength(50, ErrorMessage = "Name length should max 50 charecter long.")]
        public string NAME { get; set; }
        [Required(ErrorMessage = "Address should not be blank.")]
        [DataType(DataType.MultilineText)]
        public string ADDRESS { get; set; }
        [Required(ErrorMessage = "Password should not be blank.")]
        [StringLength(8,MinimumLength =6,ErrorMessage ="Password length between 6 to 8 charecters long.")]
        [DataType(DataType.Password)]
        public string PASSWORD { get; set; }
        [Required(ErrorMessage = "Confirm password should not be blank.")]
        [Display(Name ="CONFIRM PASSWORD")]
        [DataType(DataType.Password)]
        [Compare("PASSWORD")]
        public string CPASSWORD { get; set; }
        [Required(ErrorMessage = "Please select a gender.")]
        public string GENDER { get; set; }
        [Required(ErrorMessage = "Please select a country.")]
        [Display(Name ="COUNTRY")]
        public int? CID { get; set; }
        public List<SelectListItem> LCID { get; set; }
        [Required(ErrorMessage = "Please select a state.")]
        [Display(Name = "STATE")]
        public int? SID { get; set; }
        public List<SelectListItem> LSID { get; set; }
    }
}

Controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace WebApplication1.Controllers
{
    public class TestController : Controller
    {
        private IRepository<EMP> iRepository;
        private IRepository<COUNTRY> cRepository;
        private IRepository<STATE> sRepository;
        public TestController(IRepository<EMP> Irepository, IRepository<COUNTRY> Crepository, IRepository<STATE> Srepository)
        {
            iRepository = Irepository;
            cRepository = Crepository;
            sRepository = Srepository;
        }
        [HttpGet]
        public  IActionResult Index()
        {
            return View(iRepository.Gets());
        }
        [HttpGet]
        public JsonResult Fillddl(int CID)
        {
             return Json(JsonConvert.SerializeObject(sRepository.Gets().Where(m => m.CID == CID).ToList()));
        }
        [HttpGet]
        public IActionResult Create()
        {

            EMPVM vm = new EMPVM();
            vm.LCID = cRepository.Gets().Select(m => new SelectListItem { Value=m.CID.ToString(), Text=m.CNAME }).ToList();
            return View(vm);
        }
        [HttpGet]
        public IActionResult Delete(int id)
        {
            iRepository.Delete(id);
            return RedirectToAction("Index");
        }

        [HttpGet]
        public IActionResult Edit(int id)
        {

            EMPVM vm = new EMPVM();
            EMP data = iRepository.Get(id).Result;
            vm.EID = data.EID;
            vm.NAME = data.NAME;
            vm.ADDRESS = data.ADDRESS;
            vm.PASSWORD = data.PASSWORD;
            vm.GENDER = data.GENDER;
            vm.LCID = cRepository.Gets().Select(m => new SelectListItem { Value = m.CID.ToString(), Text = m.CNAME }).ToList();
            vm.CID = data.CID;
            vm.LSID = sRepository.Gets().Select(m => new SelectListItem { Value = m.SID.ToString(), Text = m.SNAME }).ToList();
            vm.SID = data.SID;
            return View(vm);
        }
        [HttpPost]
        public IActionResult Create(EMPVM vm)
        {
            if (ModelState.IsValid)
            {
                EMP emp = new EMP();
                emp.NAME = vm.NAME;
                emp.ADDRESS = vm.ADDRESS;
                emp.PASSWORD = vm.PASSWORD;
                emp.GENDER = vm.GENDER;
                emp.CID = vm.CID??0;
                emp.SID = vm.SID ?? 0;
                iRepository.Save(emp);
                return RedirectToAction("Index");
            }
            return View(vm);
        }
        [HttpPost]
        public IActionResult Edit(EMPVM vm)
        {
            ModelState.Remove("PASSWORD");
            ModelState.Remove("CPASSWORD");
            if (ModelState.IsValid)
            {
                EMP emp = iRepository.Get(vm.EID).Result;
                emp.NAME = vm.NAME;
                emp.ADDRESS = vm.ADDRESS;
                emp.GENDER = vm.GENDER;
                emp.CID = vm.CID ?? 0;
                emp.SID = vm.SID ?? 0;
                iRepository.Update(emp);
                return RedirectToAction("Index");
            }
            return View(vm);
        }
    }

}

Create view:

@model WebApplication1.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="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">
                <label asp-for="ADDRESS" class="control-label"></label>
                <textarea asp-for="ADDRESS" class="form-control"></textarea>
                <span asp-validation-for="ADDRESS" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PASSWORD" class="control-label"></label>
                <input asp-for="PASSWORD" class="form-control" />
                <span asp-validation-for="PASSWORD" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="CPASSWORD" class="control-label"></label>
                <input asp-for="CPASSWORD" class="form-control" />
                <span asp-validation-for="CPASSWORD" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="GENDER" class="control-label"></label>
                <input type="radio" value="Male" asp-for="GENDER" />Male
                <input type="radio" value="Female" asp-for="GENDER" />Female
                <span asp-validation-for="GENDER" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="CID" class="control-label"></label>
                <select asp-for="CID" asp-items="Model.LCID" class="form-control">
                    <option value="">Select</option>

                </select>
                <span asp-validation-for="CID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SID" class="control-label"></label>
                <select asp-for="SID" asp-items="Model.LSID" class="form-control">
                    <option value="">Select</option>
                </select>
                <span asp-validation-for="SID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

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



@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        $(function () {

            $('#CID').change(function () {
                            $.ajax({

                url: '@Url.Action("Fillddl", "Test")',

              data: { CID: $(this).val() },

                type: 'GET',

                dataType: 'json',

                contentType: 'application/json; charset=utf-8',

                success: function (result) {

                    $('#SID').empty();

                    $('#SID').append("<option value=''>Select</option>");

                    $.each(JSON.parse(result), function (i, j) {

                        $('#SID').append("<option value='" + j.SID + "'>" + j.SNAME + "</option>");

                    });

                }

            });

            });
        });
    </script>
}

Edit View :

@model WebApplication1.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">
                <input type="hidden" asp-for="EID" />
                <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">
                <label asp-for="ADDRESS" class="control-label"></label>
                <textarea asp-for="ADDRESS" class="form-control"></textarea>
                <span asp-validation-for="ADDRESS" class="text-danger"></span>
            </div>
            
            <div class="form-group">
                <label asp-for="GENDER" class="control-label"></label>
                <input type="radio" value="Male" asp-for="GENDER" />Male
                <input type="radio" value="Female" asp-for="GENDER" />Female
                <span asp-validation-for="GENDER" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="CID" class="control-label"></label>
                <select asp-for="CID" asp-items="Model.LCID" class="form-control">
                    <option value="">Select</option>

                </select>
                <span asp-validation-for="CID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SID" class="control-label"></label>
                <select asp-for="SID" asp-items="Model.LSID" class="form-control">
                    <option value="">Select</option>
                </select>
                <span asp-validation-for="SID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

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



@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        $(function () {

            $('#CID').change(function () {
                            $.ajax({

                url: '@Url.Action("Fillddl", "Test")',

              data: { CID: $(this).val() },

                type: 'GET',

                dataType: 'json',

                contentType: 'application/json; charset=utf-8',

                success: function (result) {

                    $('#SID').empty();

                    $('#SID').append("<option value=''>Select</option>");

                    $.each(JSON.parse(result), function (i, j) {

                        $('#SID').append("<option value='" + j.SID + "'>" + j.SNAME + "</option>");

                    });

                }

            });

            });
        });
    </script>
}

Index View :
@model IEnumerable<WebApplication1.Models.EMP>

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


<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.EID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.NAME)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ADDRESS)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.PASSWORD)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.GENDER)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.SID)
            </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.DisplayFor(modelItem => item.ADDRESS)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.PASSWORD)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.GENDER)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.SID)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.EID }) |

                @Html.ActionLink("Delete", "Delete", new { id=item.EID })
            </td>
        </tr>
}
    </tbody>
</table>






No comments:

Post a Comment