Continue! The previous article, today, I'm share a example simple use Repository Pattern in ASP.NET MVC 5
you can see here: Login and Register using ASP.NET MVC 5
Repository Pattern: used to create an abstract layer ( abstraction layer ), then a logical class inherits the imaginary layer and sets the functions for that layer. Implement properties for that class
In the abstraction layer, we declare the functions to use, for example: (GetAll, Insert, Update, Delete). The logical class will inherit from the abstract class, setting properties for the functions declared inside the class.
Open DB_Entities.cs file, update the following code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ProjectMVC5.Models
{
public class DB_Entities: DbContext
{
public DB_Entities() : base("DatabaseMVC5") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<DB_Entities>(null);
modelBuilder.Entity<User>().ToTable("Users");
base.OnModelCreating(modelBuilder);
}
}
}
Create Repositories in folder in project , ProjectMVC5 / Repositories . Then create IRepositories.cs file and set the functions that need to be implemented at the logical layer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectMVC5.Models;
namespace ProjectMVC5.Repositories
{
public interface IRepository<T> where T : class
{
IEnumerable<T> GetAll();
T GetById(int id);
void Insert(T obj);
void Update(T obj);
void Delete(int obj);
void Save();
}
}
Create GenericRepository.cs file in Repositories directory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectMVC5.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ProjectMVC5.Repositories
{
public class GenericRepository<T> : IRepository<T> where T: class
{
public DB_Entities _context = null;
public DbSet<T> table = null;
public GenericRepository()
{
this._context = new DB_Entities();
this._context.Configuration.ValidateOnSaveEnabled = false;
this.table = _context.Set<T>();
}
public GenericRepository(DB_Entities _context)
{
this._context = _context;
this.table = _context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return table.ToList();
}
public T GetById(int id)
{
return table.Find(id);
}
public void Insert(T obj)
{
table.Add(obj);
}
public void Update(T obj)
{
table.Attach(obj);
_context.Entry(obj).State = EntityState.Modified;
}
public void Delete(int id)
{
var data = table.Find(id);
table.Remove(data);
}
public void Save()
{
_context.SaveChanges();
}
}
}
In this code we implemented handle the connection to the database, and deployment functions are installed in the class categories original object
Previous article I have written how to check email users
Create IUserRepository.cs (abstraction layer) file class in Repositories folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectMVC5.Models;
namespace ProjectMVC5.Repositories
{
public interface IUserRepository : IRepository<User>
{
User WhereEmail(string email);
IEnumerable<User> CheckLogin(string email, string password);
}
}
WhereEmail (): use to check Email exists in the database or not
CheckLogin (): use to check user login
Remember, when you created a abstraction layer class and write a function in that class.
Then you must also create a class inheriting from that class, to implement writing features for that class.
Create UserRepository.cs file in Repositories folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectMVC5.Models;
namespace ProjectMVC5.Repositories
{
public class UserRepository: GenericRepository<User>,IUserRepository
{
public User WhereEmail(string email)
{
var data = table.FirstOrDefault(s => s.Email == email);
return data;
}
public IEnumerable<User> CheckLogin(string email, string password)
{
var data = table.Where(s => s.Email.Equals(email) && s.Password.Equals(password)).ToList();
return data;
}
}
}
Okay, you config Repository success, now we need see HomeController.cs file in Controllers folder and edit it, you can see it: Login and Register using ASP.NET MVC 5
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectMVC5.Models;
using System.Security.Cryptography;
using ProjectMVC5.Repositories;
namespace ProjectMVC5.Controllers
{
public class HomeController : Controller
{
private GenericRepository<User> repository = null;
private UserRepository userRepository = null;
public HomeController()
{
this.userRepository = new UserRepository();
this.repository = new GenericRepository<User>();
}
public HomeController(GenericRepository<User> repository, UserRepository userRepository)
{
this.repository = repository;
this.userRepository = userRepository;
}
public ActionResult Index()
{
if (Session["idUser"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}
//GET: Register
public ActionResult Register()
{
return View();
}
//POST: Register
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(User _user)
{
if (ModelState.IsValid)
{
var check = userRepository.WhereEmail(_user.Email);
if (check == null)
{
_user.Password = GetMD5(_user.Password);
userRepository.Insert(_user);
userRepository.Save();
return RedirectToAction("Index");
}
else
{
ViewBag.error = "Email already exists";
return View();
}
}
return View();
}
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(string email,string password)
{
if (ModelState.IsValid)
{
var f_password = GetMD5(password);
var data = userRepository.CheckLogin(email, f_password);
if (data.Count() > 0)
{
//add session
Session["FullName"] = data.FirstOrDefault().FirstName +" "+ data.FirstOrDefault().LastName;
Session["Email"] = data.FirstOrDefault().Email;
Session["idUser"] = data.FirstOrDefault().idUser;
return RedirectToAction("Index");
}
else
{
ViewBag.error = "Login failed";
return RedirectToAction("Login");
}
}
return View();
}
//Logout
public ActionResult Logout()
{
Session.Clear();//remove session
return RedirectToAction("Login");
}
//create a string MD5
public static string GetMD5(string str)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] fromData = Encoding.UTF8.GetBytes(str);
byte[] targetData = md5.ComputeHash(fromData);
string byte2String = null;
for (int i = 0; i < targetData.Length; i++)
{
byte2String += targetData[i].ToString("x2");
}
return byte2String;
}
}
}
Ok that's it! This article is a bit complicated, you can see the article before, after then see to Repository, you will visualize and understand its steps.
You can see: ASP.NET MVC 5 Repository Pattern
Top comments (0)