Please have a through look my custom implementation of generic repository pattern and suggest anything I may be lacking.
- I am using a generic interface with 6 methods
- I'll be using a repository class for each entity type (e.g
UserRepository
,ProductRepository
,StoreRepository
) which are not only going to implement the generic interface but also can add additional methods as per the need with respect to each repository class. for example:UserRepository
can add a new method named asCountUsers()
which gets called from controller.ProductRepository
can add a new method named asGetExpiredProducts()
which gets called from controller.
- I am declaring
IGenericRepository<User>
inUserController
, similarly in other controllers and usingrepositoryPattern
.
Generic Repository Interface
public interface IGenericRepository<T> : IDisposable where T : class
{
IEnumerable<T> SelectAll();
T SelectByID(object id);
void Insert(T obj);
void Update(T obj);
void Delete(object id);
void Save();
}
Implementation of Generic Repository Interface
public class UserRepository : IGenericRepository<User>
{
private ModelDBEntities dataContext = null;
public UserRepository()
{
this.dataContext = new ModelDBEntities();
}
public UserRepository(ModelDBEntities dataContext)
{
this.dataContext = dataContext;
}
public IEnumerable<User> SelectAll()
{
return dataContext.Users;
}
public User SelectByID(object argId)
{
long userId = long.Parse(argId.ToString());
return dataContext.Users.Single(u => u.UserId == userId);
}
public void Insert(User obj)
{
dataContext.Users.AddObject(obj);
}
public void Update(User obj)
{
if (obj.EntityState == EntityState.Detached)
dataContext.Users.Attach(obj);
dataContext.ObjectStateManager.ChangeObjectState(obj, System.Data.EntityState.Modified);
}
public void Delete(object argUserId)
{
long userId = long.Parse(argUserId.ToString());
dataContext.Users.Single(u => u.UserId == userId).Status = "inactive";
}
public void Save()
{
dataContext.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
dataContext.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
My User Controller
public class UserController : Controller
{
private IGenericRepository<User> _repositoryUser = null;
public UserController()
{
_repositoryUser = new UserRepository();
}
public UserController(IGenericRepository<User> repository)
{
_repositoryUser = repository;
}
[HttpPost]
public JsonResult SubmitHandler(User argUser)
{
if (ModelState.IsValid)
{
_repositoryUser.Insert(argUser);
_repositoryUser.Save();
return Json("success");
}
else
return Json("failure");
}
public ActionResult Delete(object Id)
{
if (Id != null && Id.ToString().Trim().Length > 0)
{
int param = int.Parse(Id.ToString());
_repositoryUser.Delete(Id as object);
_repositoryUser.Save();
return View("User", _repositoryUser.SelectAll());
}
else
return View("404");
}
}