NHibernate Repository

♀尐吖头ヾ 提交于 2019-12-05 02:55:43

问题


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


回答1:


See these:

  • Data Access With NHibernate

  • Repository Pattern in NHibernate

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



来源:https://stackoverflow.com/questions/6543436/nhibernate-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!