sexta-feira, 24 de julho de 2015

NHibernate - RepositoryBase

using NHibernate;
using System.Collections.Generic;

namespace Lapuinka.Data
{
    public abstract class RepositoryBase where TEntity : EntityBase
    {
        public ISession Session { get; private set; }

        protected RepositoryBase()
        {
            Session = SessionManager.Instance.Session;
        }

        protected RepositoryBase(ISession session)
        {
            Session = session;
        }

        public TEntity Save(TEntity entity)
        {          
            using (var transaction = new TransactionRequired(Session))
            {
                Session.Save(entity);
                transaction.Commit();
            }
           
            return entity;
        }

        public TEntity Update(TEntity entity)
        {
            using (var transaction = new TransactionRequired(Session))
            {
                Session.Update(entity);
                transaction.Commit();
            }
           
            return entity;
        }

        public TEntity SaveOrUpdate(TEntity entity)
        {
            using (var transaction = new TransactionRequired(Session))
            {
                Session.SaveOrUpdate(entity);
                transaction.Commit();
            }

            return entity;
        }

        public void Delete(TEntity entity)
        {
            using (var transaction = new TransactionRequired(Session))
            {
                Session.Delete(entity);
                transaction.Commit();
            }
        }

        public TEntity GetById(TId id)
        {
            return Session.Get(id);
        }

        public IList GetAll()
        {
            return Session.CreateCriteria(typeof(TEntity)).List();
        }
    }

}
Postar um comentário