Reputation: 461
Does anybody has proper and simplified write up on NHibernate Repository? I've used Java, Hibernate, LCDS DataService Repositories with FlexBuilder (using rtmp channelling) and want to implement the exact fundamental with C#.NET.
I've gone through lots of online documentation but nothing was reflecting the exact use like with FlexBuilder.
If anybody has a small example application then do share. That would be much helpful.
Regards Nitin
Upvotes: 3
Views: 12028
Reputation: 79889
See these:
First Create an interface IRepository
:
public interface IRepository<T>
{
int Add(T entity);
void Delete(T entity);
void Update(T entity);
T GetById(int id);
IEnumerable<T> FindAll(DetachedCriteria criteria);
...
.
.
//
}
Then implement this interface as following:
public class Repository<T> : IRepository<T>
{
readonly IActiveSessionManager _activeSessionManager;
protected ISession Session
{
get { return _activeSessionManager.GetActiveSession(); }
}
public Repository(IActiveSessionManager activeSessionManager)
{
_activeSessionManager = activeSessionManager;
}
public int Add(T entity)
{
int newId = (int)Session.Save(entity);
Session.Flush();
return newId;
}
.
.
// add the remaining implementations
}
The implementation of the ActiveSessionManager
and SessionProvider
is very simple and you can find it in the previous links.
You can expose your methods as following:
public T FindOne(NHibernate.Criterion.DetachedCriteria criteria)
{
return criteria.GetExecutableCriteria(Session).UniqueResult<T>();
}
Then:
public class EntityRepository : Repository<Entity>
{
public EntityRepository(IActiveSessionManager activeSessionManger)
: base(activeSessionManger)
{
}
public Entity GetByName(string name)
{
var criteria = NHibernate.Criterion.DetachedCriteria.For<Entity>()
.Add(Restrictions.Eq("name", name));
return FindOne(criteria);
}
public IList<Entity> returnsomething()
{
}
....
}
This is a basic implementation for this pattern, but you can decorate it as your design drive you.
You can go further, I recommend, after understanding these pattern and implement it, checking out NHibernate and the Unit of Work Pattern
Upvotes: 18