c# repository code example
Example: generic repository pattern c#
namespace RepositoryUsingEFinMVC.GenericRepository
{
public interface IGenericRepository<T> where T : class
{
IEnumerable<T> GetAll();
T GetById(object id);
void Insert(T obj);
void Update(T obj);
void Delete(object id);
void Save();
}
}
namespace RepositoryUsingEFinMVC.GenericRepository
{
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private EmployeeDBContext _context = null;
private DbSet<T> table = null;
public GenericRepository()
{
this._context = new EmployeeDBContext();
table = _context.Set<T>();
}
public GenericRepository(EmployeeDBContext _context)
{
this._context = _context;
table = _context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return table.ToList();
}
public T GetById(object 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(object id)
{
T existing = table.Find(id);
table.Remove(existing);
}
public void Save()
{
_context.SaveChanges();
}
}
}
using System.Web.Mvc;
using RepositoryUsingEFinMVC.DAL;
using RepositoryUsingEFinMVC.GenericRepository;
namespace RepositoryUsingEFinMVC.Controllers
{
public class EmployeeController : Controller
{
private IGenericRepository<Employee> repository = null;
public EmployeeController()
{
this.repository = new GenericRepository<Employee>();
}
public EmployeeController(IGenericRepository<Employee> repository)
{
this.repository = repository;
}
[HttpGet]
public ActionResult Index()
{
var model = repository.GetAll();
return View(model);
}
[HttpGet]
public ActionResult AddEmployee()
{
return View();
}
[HttpPost]
public ActionResult AddEmployee(Employee model)
{
if (ModelState.IsValid)
{
repository.Insert(model);
repository.Save();
return RedirectToAction("Index", "Employee");
}
return View();
}
[HttpGet]
public ActionResult EditEmployee(int EmployeeId)
{
Employee model = repository.GetById(EmployeeId);
return View(model);
}
[HttpPost]
public ActionResult EditEmployee(Employee model)
{
if (ModelState.IsValid)
{
repository.Update(model);
repository.Save();
return RedirectToAction("Index", "Employee");
}
else
{
return View(model);
}
}
[HttpGet]
public ActionResult DeleteEmployee(int EmployeeId)
{
Employee model = repository.GetById(EmployeeId);
return View(model);
}
[HttpPost]
public ActionResult Delete(int EmployeeID)
{
repository.Delete(EmployeeID);
repository.Save();
return RedirectToAction("Index", "Employee");
}
}
}