ASP .NET Core Repository

Introduction

 
In this article, we will create 4 projects (Main, Core, Data, and Infrastructure) using ASP .NET Core Repository
 
Step 1: Open Visual Studio 
 
Step 2: Create a New Project 
 
Step 3: Select Project Type in Visual Studio web and set to ASP.NET Core Web Application. Set the name and press Ok.
 
image1 
 
Step 4: Choose the .Net core and ASP.NET Core 2.2 and press Ok.
 
image2
 
Step 5: Right-click on Solution and select ADD => New Project
 
image3 
 
Step 6: Select Visual C# in .NET Core and select Class Library(.NET Core), then write the project name and click OK.
 
 image4
 
Step 7: Now next add another project the same as in Step 5 and Step 6, but with a different project name (Repositry.Infrastructure AND Repositry.Data).
 
image5 
 
Now we can create the Models Class:
  • Models: Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in an SQL Server database.
  • Now in Repositry.Data, right-click and add a New Folder name in Models, Models => Add => Class. Set the class name
image6
 
  • Now one-by-one, create All Models Class (Registration, Product, Category ) and write your code
Below shows a screenshot for all four classes:
 
RegistrationMaster.cs
 
image7 
 
CategoryMaster.cs
 
image8 
 
ProductMaster.cs
 
image9 
 
The next step is to add interface in Repository.Core. Right-click on Repository.Core and add a New folder, Rename to Interface then Add Class in Interface IRegistrationRepository.cs. Create all methods we can use in Project (e.x GetAll, GetById, Create .etc)
 
image10 
 
Repository.Core work is now complete. Turn to Repository.Infrastructure 
  • Repository.Infrastructure
In Repository.Infrastructure, first add a reference for data use of another project. We will use data of Repository.Core, so add a reference. First right-click on References => Add Reference, then Click check box of Repository.Core, shown in the below 2 screenshots;
 
image11 
 
Then
 
image12 
 
Now we will Add a new folder and Rename it to Context and add Context Class  
 
image13
 
Now we can add a Repository Folder in Repository.Infrastructure
 
After adding, use Namespace 
 
image14 
 
IRegistrationRepository.cs
  1. using Repository.Core.Interface;  
  2. using Repositry.Data.Models;  
  3. using Repositry.Infrastructure.Contexts;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Linq;  
  7. using System.Text;  
  8.   
  9. namespace Repositry.Infrastructure.Repository  
  10. {  
  11.     public class RegistrationRepository : IRegistrationRepository  
  12.     {  
  13.         private readonly Context context;  
  14.         public RegistrationRepository(Context _context)  
  15.         {  
  16.             context = _context;  
  17.         }  
  18.         public RegistrationMaster Create(RegistrationMaster User)  
  19.         {  
  20.             context.RegistrationMaster.Add(User);  
  21.             context.SaveChanges();  
  22.             return User;  
  23.         }  
  24.         public IQueryable<RegistrationMaster> GETALL()  
  25.         {  
  26.             return context.RegistrationMaster;  
  27.         }  
  28.         public RegistrationMaster GetId(int id)  
  29.         {  
  30.             return context.RegistrationMaster.Find(id);  
  31.         }  
  32.         public void Save()  
  33.         {  
  34.             context.SaveChanges();  
  35.         }  
  36.     }  
CategoryRepository.cs
  1. using Repository.Core.Interface;  
  2. using Repositry.Data.Models;  
  3. using Repositry.Infrastructure.Contexts;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Linq;  
  7. using System.Text;  
  8.   
  9. namespace Repositry.Infrastructure.Repository  
  10. {  
  11.     public class CategoryRepository : ICategoryRepository  
  12.     {  
  13.         private readonly Context context;  
  14.         public CategoryRepository(Context _context)  
  15.         {  
  16.             context = _context;  
  17.         }  
  18.         public CategoryMaster Create(CategoryMaster User)  
  19.         {  
  20.             context.CategoryMaster.Add(User);  
  21.             context.SaveChanges();  
  22.             return User;  
  23.         }  
  24.         public IQueryable<CategoryMaster> GETALL()  
  25.         {  
  26.             return context.CategoryMaster;  
  27.         }  
  28.         public CategoryMaster GetId(int id)  
  29.         {  
  30.             return context.CategoryMaster.Find(id);  
  31.         }  
  32.         public CategoryMaster Delete(int id)  
  33.         {  
  34.             CategoryMaster User = context.CategoryMaster.Find(id);  
  35.             if (User != null)  
  36.             {  
  37.                 context.CategoryMaster.Remove(User);  
  38.                 Save();  
  39.             }  
  40.             return User;  
  41.         }  
  42.         public void Save()  
  43.         {  
  44.             context.SaveChanges();  
  45.         }  
  46.     }  
Repository. Infrastructure Work is complete 
 
Next, add Startup.cs
 
Services in add  connection and DependencyInjection
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddDbContext<Context>(options => options.UseSqlServer(Configuration.GetConnectionString("Connection")));  
  4.             services.Configure<CookiePolicyOptions>(options =>  
  5.             {  
  6.                 // This lambda determines whether user consent for non-essential cookies is needed for a given request.  
  7.                 options.CheckConsentNeeded = context => true;  
  8.                 options.MinimumSameSitePolicy = SameSiteMode.None;  
  9.             });  
  10.             services.AddSession(options =>  
  11.             {  
  12.                 options.IdleTimeout = TimeSpan.FromMinutes(20);  
  13.                 options.Cookie.HttpOnly = true;  
  14.                 options.Cookie.IsEssential = true;  
  15.   
  16.             });  
  17.             services.AddTransient<IRegistrationRepository, RegistrationRepository>();  
  18.             services.AddTransient<ICategoryRepository, CategoryRepository>();  
  19.             services.AddTransient<IProductRepository, ProductRepository>();  
  20.             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);  
  21.         } 
  • Repository
Now turn to your Main Project Repository. First add to references of both of Project Repository.Core and Repository.Infrastructure shown in the below screenshot:
 
IMAGE15 
 
Now Create Controller:
 
Create all the controllers that needed for the project. When we create a controller, don’t remove Controller e.x HomeController. If we create any controller, only add the name before Controller:
 
Add Controller: Right Click on Controller Folder => Add => Controller, select MVC5 Controller, empty, then add  
 
Set your controller name (but do not delete Controller)
 
RegistrationController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text.RegularExpressions;  
  5. using System.Threading.Tasks;  
  6. using System.Web;  
  7. using Microsoft.AspNetCore.Mvc;  
  8. using Repository.Core.Interface;  
  9. using Repositry.Data.Models;  
  10.   
  11. namespace Repository.Controllers  
  12. {  
  13.     public class RegistrationController : Controller  
  14.     {  
  15.         private readonly IRegistrationRepository _REG;  
  16.         public RegistrationController(IRegistrationRepository REG)  
  17.         {  
  18.             _REG = REG;  
  19.         }  
  20.         public IActionResult Index()  
  21.         {  
  22.   
  23.             return View();  
  24.         }  
  25.         [HttpPost]  
  26.         public IActionResult Index(RegistrationMaster UserREG)  
  27.         {  
  28.             var con1 = UserREG.USRContact;  
  29.   
  30.             if (con1 == null)  
  31.             {  
  32.                 ViewBag.Error = "Please Enter Contact_No";  
  33.                 return View();  
  34.             }  
  35.             else  
  36.             {  
  37.                 string conRegex = @"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$";  
  38.                 Regex re = new Regex(conRegex);  
  39.                 if (!re.IsMatch(con1))  
  40.                 {  
  41.                     ViewBag.Error = "Contact No is not valid";  
  42.                     return View();  
  43.                 }  
  44.             }             
  45.             var mail = UserREG.USREmail;  
  46.             if (mail == null)  
  47.             {  
  48.                 ViewBag.Error = "Please Enter Email_Id";  
  49.                 return View();  
  50.             }  
  51.             else  
  52.             {  
  53.                 string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +  
  54.                                    @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +  
  55.                                       @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";  
  56.                 Regex re = new Regex(emailRegex);  
  57.                 if (!re.IsMatch(mail))  
  58.                 {  
  59.                     var error = "Email is not valid";  
  60.                     return Json(new { emvalid = true, error });  
  61.                 }  
  62.             }  
  63.             var e = _REG.GETALL().Any(i => i.USREmail == mail);  
  64.             if (e)  
  65.             {  
  66.                 return Json(new { EmailExists = true });  
  67.             }  
  68.   
  69.             UserREG.USRCreateDate = DateTime.Now;  
  70.             UserREG.USRUpdateDate = DateTime.Now;  
  71.             _REG.Create(UserREG);  
  72.             UserREG.USREnc = enc10.Encrypt(UserREG.USRId);  
  73.             var pass = HttpUtility.UrlEncode(Encryption.Encrypt(UserREG.USRPassword));  
  74.             UserREG.USRPassword = pass;  
  75.             _REG.Save();  
  76.             return Redirect("/Login");  
  77.         }  
  78.   
  79.     }  
  80.  
Login.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text.RegularExpressions;  
  5. using System.Threading.Tasks;  
  6. using System.Web;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.AspNetCore.Mvc;  
  9. using Repository.Core.Interface;  
  10. using Repositry.Data.Models;  
  11.   
  12. namespace Repository.Controllers  
  13. {  
  14.     public class LoginController : Controller  
  15.     {  
  16.         private readonly IRegistrationRepository _REG;  
  17.         public LoginController(IRegistrationRepository REG)  
  18.         {  
  19.             _REG = REG;  
  20.         }  
  21.         public IActionResult Index()  
  22.         {  
  23.             return View();  
  24.         }  
  25.         public IActionResult Index(RegistrationMaster User)  
  26.         {  
  27.   
  28.             if (User.USREmail != null)  
  29.             {  
  30.                 string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +  
  31.                                       @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +  
  32.                                          @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";  
  33.                 Regex re = new Regex(emailRegex);  
  34.                 if (!re.IsMatch(User.USREmail))  
  35.                 {  
  36.                     ViewBag.Error = "Email is not valid";  
  37.                     return View();  
  38.                 }  
  39.                 else  
  40.                 {  
  41.                     if (User.USRPassword != null)  
  42.                     {  
  43.                         string Email = User.USREmail;  
  44.                         string Password = HttpUtility.UrlEncode(Encryption.Encrypt(User.USRPassword));  
  45.                         //string Password = companymaster.CMPREGPassword;  
  46.   
  47.                         var USER = _REG.GETALL().Where(a => a.USREmail == Email && a.USRPassword == Password).FirstOrDefault();  
  48.   
  49.                         if (USER != null)  
  50.                         {  
  51.                              
  52.                          
  53.                                 HttpContext.Session.SetString("USRId", USER.USRId.ToString());  
  54.                                 HttpContext.Session.SetString("USRName", USER.USRName);  
  55.                                 HttpContext.Session.SetString("USREnc", USER.USREnc);  
  56.   
  57.                                 return Redirect("/Welcome");                             
  58.                               
  59.                         }  
  60.                         else  
  61.                         {  
  62.                             ViewBag.Error = "Account Invalid";  
  63.   
  64.                             return View();  
  65.                         }  
  66.                     }  
  67.   
  68.                     else  
  69.                     {  
  70.                         ViewBag.Error = "please Enter the Password";  
  71.                         return View();  
  72.                     }  
  73.                 }  
  74.             }  
  75.             else  
  76.             {  
  77.                 ViewBag.Error = "Please Enter the Email";  
  78.                 return View();  
  79.             }  
  80.         }  
  81.     }  
  82.  
Login Page
 
image16
 
 
UName: maulikprajapati233@gmail.com         pass:123456
 
Login Welcome User Page
 
image17 
 
Sign-Up Page
 
image18 
 

Category Controller

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Http;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. using Repository.Core.Interface;  
  8. using Repository.Data.Models;  
  9.   
  10. namespace Repository.Controllers  
  11. {  
  12.     public class CategoryController : Controller  
  13.     {  
  14.         private readonly ICategoryRepository _Cat;  
  15.         public CategoryController(ICategoryRepository Cat)  
  16.         {  
  17.             _Cat = Cat;  
  18.         }  
  19.         public IActionResult Index()  
  20.         {  
  21.             if (HttpContext.Session.GetString("USRId") != null)  
  22.             {  
  23.                 var id = Convert.ToInt32(HttpContext.Session.GetString("USRId"));  
  24.                 var cat = _Cat.GETALL().Where(c=>c.USRId==id).ToList();  
  25.                 return View(cat);  
  26.             }  
  27.             else  
  28.             {  
  29.                 return Redirect("/Login");  
  30.             }  
  31.   
  32.         }  
  33.         public IActionResult Create()  
  34.         {  
  35.             if (HttpContext.Session.GetString("USRId") != null)  
  36.             {  
  37.                 return View();  
  38.             }  
  39.             else  
  40.             {  
  41.                 return Redirect("/Login");  
  42.             }  
  43.         }  
  44.         [HttpPost]  
  45.         public IActionResult Create(CategoryMaster Cat)  
  46.         {  
  47.             if (HttpContext.Session.GetString("USRId") != null)  
  48.             {  
  49.                 var id = Convert.ToInt32(HttpContext.Session.GetString("USRId"));  
  50.                 Cat.USRId = id;  
  51.                 Cat.USRCreateDate = DateTime.Now;  
  52.                 Cat.USRUpdateDate = DateTime.Now;  
  53.                 Cat.CATIsActive = true;  
  54.                 _Cat.Create(Cat);  
  55.                 Cat.CATEnc = enc10.Encrypt(Cat.CATId);  
  56.                 _Cat.Save();  
  57.                 return Redirect("/Category");  
  58.             }  
  59.             else  
  60.             {  
  61.                 return Redirect("/Login");  
  62.             }  
  63.         }  
  64.         public IActionResult Edit(string Id)  
  65.         {  
  66.             if (HttpContext.Session.GetString("USRId") != null)  
  67.             {  
  68.                 var id = enc10.Decrypt(Id);  
  69.                 var data = _Cat.GetId(id);  
  70.   
  71.                 return View(data);  
  72.             }  
  73.             else  
  74.             {  
  75.                 return Redirect("/Login");  
  76.             }  
  77.         }  
  78.         [HttpPost]  
  79.         public IActionResult Edit(CategoryMaster cat)  
  80.         {  
  81.             if (HttpContext.Session.GetString("USRId") != null)  
  82.             {  
  83.                 var cat1 = _Cat.GetId(cat.CATId);  
  84.                 cat1.CATName = cat.CATName;  
  85.                 cat1.CATIsActive = cat.CATIsActive;  
  86.                 cat1.USRUpdateDate = DateTime.Now;  
  87.                 _Cat.Save();  
  88.                 return Redirect("/Category");  
  89.             }  
  90.             else  
  91.             {  
  92.                 return Redirect("/Login");  
  93.             }  
  94.         }  
  95.         public IActionResult Delete(string Id)  
  96.         {  
  97.             if (HttpContext.Session.GetString("USRId") != null)  
  98.             {  
  99.                 var id = enc10.Decrypt(Id);  
  100.                 var data = _Cat.GetId(id);  
  101.                 _Cat.Delete(id);  
  102.                 _Cat.Save();  
  103.                 return Redirect("/Category");  
  104.             }  
  105.             else  
  106.             {  
  107.                 return Redirect("/Login");  
  108.             }  
  109.         }  
  110.     } 
     

Create View category method Right click After add View

image19 
 
Category List Page
 
image20
 
Category Create Page
 
image21 
 
Product Controller.cs
 
Crud in Product
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Http;  
  7. using Microsoft.AspNetCore.Mvc;  
  8. using Microsoft.EntityFrameworkCore;  
  9. using Repository.Core.Interface;  
  10. using Repository.Data.Models;  
  11.   
  12. namespace Repository.Controllers  
  13. {  
  14.     public class ProductController : Controller  
  15.     {  
  16.         private readonly IProductRepository _Prd;  
  17.         private readonly ICategoryRepository _Cat;  
  18.         public ProductController(IProductRepository Prd, ICategoryRepository Cat)  
  19.         {  
  20.             _Prd = Prd;  
  21.             _Cat = Cat;  
  22.         }  
  23.         public IActionResult Index()  
  24.         {  
  25.             if (HttpContext.Session.GetString("USRId") != null)  
  26.             {  
  27.                 var id= Convert.ToInt32(HttpContext.Session.GetString("USRId"));  
  28.                 var Prd = _Prd.GETALL().Where(p=>p.USRId==id).Include(p=>p.category);  
  29.                 return View(Prd);  
  30.             }  
  31.             else  
  32.             {  
  33.                 return Redirect("/Login");  
  34.             }  
  35.   
  36.         }  
  37.         public IActionResult Create()  
  38.         {  
  39.             if (HttpContext.Session.GetString("USRId") != null)  
  40.             {  
  41.                 ViewData["Category"] = _Cat.GETALL().Where(c => c.CATIsActive.Equals(true)).ToList();  
  42.                 return View();  
  43.             }  
  44.             else  
  45.             {  
  46.                 return Redirect("/Login");  
  47.             }  
  48.         }  
  49.         [HttpPost]  
  50.         public IActionResult Create(ProductMaster Prd)  
  51.         {  
  52.             if (HttpContext.Session.GetString("USRId") != null)  
  53.             {  
  54.                 IFormFile data = Request.Form.Files["PRDImage"];  
  55.                  if (data == null || data.Length == 0)  
  56.                     return Content("file not selected");  
  57.                 Prd.USRCreateDate = DateTime.Now;  
  58.                 Prd.USRUpdateDate = DateTime.Now;  
  59.                 Prd.PRDImage = data.FileName;  
  60.                 Prd.USRId = Convert.ToInt32(HttpContext.Session.GetString("USRId"));  
  61.                 _Prd.Create(Prd);  
  62.           
  63.                 Prd.PRDEnc = enc10.Encrypt(Prd.PRDId);  
  64.                 _Prd.Save();  
  65.                  
  66.   
  67.                 var path = Path.Combine(  
  68.                             Directory.GetCurrentDirectory(), "wwwroot//Product",  
  69.                             data.FileName);  
  70.   
  71.                 using (var stream = new FileStream(path, FileMode.Create))  
  72.                 {  
  73.                    data.CopyToAsync(stream);  
  74.                 }  
  75.                 return Redirect("/Product");  
  76.             }  
  77.             else  
  78.             {  
  79.                 return Redirect("/Login");  
  80.             }  
  81.         }  
  82.         public IActionResult Edit(string Id)  
  83.         {  
  84.             if (HttpContext.Session.GetString("USRId") != null)  
  85.             {  
  86.                 var id = enc10.Decrypt(Id);  
  87.                 var data = _Prd.GetId(id);  
  88.                 ViewData["Category"] = _Cat.GETALL().Where(c => c.CATIsActive.Equals(true)).ToList();  
  89.                 return View(data);  
  90.             }  
  91.             else  
  92.             {  
  93.                 return Redirect("/Login");  
  94.             }  
  95.         }  
  96.         [HttpPost]  
  97.         public IActionResult Edit(ProductMaster Prd)  
  98.         {  
  99.             if (HttpContext.Session.GetString("USRId") != null)  
  100.             {  
  101.                 IFormFile Image = Request.Form.Files["PRDImage"];  
  102.                 if (Image == null || Image.Length == 0)  
  103.                 {  
  104.                     var prd1 = _Prd.GetId(Prd.PRDId);  
  105.                     prd1.PRDName = Prd.PRDName;  
  106.                     prd1.PRDPrice = Prd.PRDPrice;  
  107.                     prd1.PRDDescription = Prd.PRDDescription;  
  108.                     prd1.USRUpdateDate = DateTime.Now;  
  109.                     _Prd.Save();  
  110.                 }  
  111.                 else  
  112.                 {  
  113.                     var prd1 = _Prd.GetId(Prd.PRDId);  
  114.                     prd1.PRDName = Prd.PRDName;  
  115.                     prd1.PRDPrice = Prd.PRDPrice;  
  116.                     prd1.PRDDescription = Prd.PRDDescription;  
  117.                     prd1.PRDImage = Image.FileName;  
  118.                     prd1.USRUpdateDate = DateTime.Now;  
  119.                     _Prd.Save();  
  120.                     var path = Path.Combine(  
  121.                          Directory.GetCurrentDirectory(), "wwwroot//Product",  
  122.                          Image.FileName);  
  123.   
  124.                     using (var stream = new FileStream(path, FileMode.Create))  
  125.                     {  
  126.                         Image.CopyToAsync(stream);  
  127.                     }  
  128.                 }  
  129.                 
  130.                 return Redirect("/Product");  
  131.             }  
  132.             else  
  133.             {  
  134.                 return Redirect("/Login");  
  135.             }  
  136.         }  
  137.         public IActionResult Delete(string Id)  
  138.         {  
  139.             if (HttpContext.Session.GetString("USRId") != null)  
  140.             {  
  141.                 if (Id == null)  
  142.                     return NotFound();  
  143.                 if (Id.Length == 10)  
  144.                     return NotFound();  
  145.                 var id = enc10.Decrypt(Id);  
  146.   
  147.                 if (Id == null)  
  148.                     return NotFound();  
  149.                 var data = _Prd.GetId(id);  
  150.                 _Prd.Delete(id);  
  151.                 _Prd.Save();  
  152.                 return Redirect("/Product");  
  153.             }  
  154.             else  
  155.             {  
  156.                 return Redirect("/Login");  
  157.             }  
  158.         }  
  159.     }  
  160.  
Product Page
 
image22 
 
 
Add Product
 
image23