开发者

NHibernate Repository

开发者 https://www.devze.com 2023-03-16 10:11 出处:网络
Does anybody has proper and simplified write up on NHibernate Repository? I\'ve used Java, Hibernate, LCDS DataService Repositories with FlexBuilder (using rtmp chann开发者_StackOverflow中文版elling)

Does anybody has proper and simplified write up on NHibernate Repository? I've used Java, Hibernate, LCDS DataService Repositories with FlexBuilder (using rtmp chann开发者_StackOverflow中文版elling) 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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号