Skip to content

Instantly share code, notes, and snippets.

@KingsleyOmon-Edo
Forked from ChrisMcKee/Repository.cs
Created October 22, 2018 03:08
Show Gist options
  • Save KingsleyOmon-Edo/0b0ada81dcf205f1a6b1264083636791 to your computer and use it in GitHub Desktop.
Save KingsleyOmon-Edo/0b0ada81dcf205f1a6b1264083636791 to your computer and use it in GitHub Desktop.
Generic Repository Interface and implementation. NHIBERNATE
namespace Core.Repository
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
public interface IRepository<T> where T : class
{
bool Add(T entity);
bool Add(IEnumerable<T> items);
bool Update(T entity);
bool Delete(T entity);
bool Delete(IEnumerable<T> entities);
T FindBy(int id);
T FindBy<TV>(TV id);
IQueryable<T> All();
T FindBy(Expression<Func<T, bool>> expression);
IQueryable<T> FilterBy(Expression<Func<T, bool>> expression);
}
}
namespace Data.Repository
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NHibernate;
using NHibernate.Linq;
using Core.Repository;
using Ninject;
public class Repository<T> : IRepository<T> where T : class
{
private readonly ISession _session;
private readonly IKernel _kernel;
public Repository(ISession session, IKernel kernel)
{
_session = session;
_kernel = kernel;
}
public bool Add(T entity)
{
_session.Save(entity);
_session.Flush();
return true;
}
public bool Add(IEnumerable<T> items)
{
foreach (T item in items)
{
_session.Save(item);
}
_session.Flush();
return true;
}
public bool Update(T entity)
{
_session.Update(entity);
_session.Flush();
return true;
}
public bool Delete(T entity)
{
_session.Delete(entity);
_session.Flush();
return true;
}
public bool Delete(IEnumerable<T> entities)
{
foreach (T entity in entities)
{
_session.Delete(entity);
}
_session.Flush();
return true;
}
public T FindBy(int id)
{
_session.CacheMode = CacheMode.Normal;
return _session.Get<T>(id);
}
public T FindBy<TV>(TV id)
{
return _session.Get<T>(id);
}
public IQueryable<T> All()
{
return _session.Query<T>();
}
public T FindBy(Expression<Func<T, bool>> expression)
{
return FilterBy(expression).FirstOrDefault();
}
public IQueryable<T> FilterBy(Expression<Func<T, bool>> expression)
{
return All().Where(expression).AsQueryable();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment