HomeController:-
public class HomeController : Controller
{
private IUnitOfWork _unitOfWork;
public HomeController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public ActionResult Index()
{
Category modelList = _unitOfWork.RepositoryFor<Category>().GetById(5);
var objResult = _unitOfWork.RepositoryFor<Category>().GetAll();
return View(modelList);
}
}
IUnitOfWork:-
public interface IUnitOfWork
{
IGenericRepository<T> RepositoryFor<T>() where T : class;
void SaveChanges();
}
UnitOfWork:-
public class UnitOfWork : IUnitOfWork, System.IDisposable
{
private readonly NORTHWNDEntities _context;
public UnitOfWork(NORTHWNDEntities context)
{
_context = context;
}
public IGenericRepository<T> RepositoryFor<T>() where T : class
{
return new GenericRepository<T>(_context);
}
public void SaveChanges()
{
_context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
System.GC.SuppressFinalize(this);
}
}
IGenericRepository:-
public interface IGenericRepository<TEntity>
{
TEntity GetById(object id);
TEntity GetFirstOrDefault(
void Insert(TEntity entity);
void Update(TEntity entity);
void Delete(object id);
List<TEntity> GetAll();
}
GenericRepository:-
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where
TEntity : class
{
private DbContext context;
private DbSet<TEntity> dbSet;
public GenericRepository(DbContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual TEntity GetById(object id)
{
return dbSet.Find(id);
}
public virtual TEntity GetFirstOrDefault(Expression<Func<TEntity, bool>>
filter = null, params Expression<Func<TEntity, object>>[] includes)
{
IQueryable<TEntity> query = dbSet;
foreach (Expression<Func<TEntity, object>> include in includes)
query = query.Include(include);
return query.FirstOrDefault(filter);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Update(TEntity entity)
{
dbSet.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual List<TEntity> GetAll()
{
return dbSet.ToList<TEntity>();
}
}