如何在Nhibernate存储库模式中使用UnitOfWork?

时间:2013-06-30 06:21:15

标签: nhibernate fluent-nhibernate repository-pattern unit-of-work

在我的存储库模式中,我合并了一个工作单元:

  public class NHibernateUnitOfWork : IUnitOfWork
{
    private readonly ISession _session;
    private ITransaction _transaction;

    public NHibernateUnitOfWork(ISession session)
    {
        _session = session;
        _transaction = _session.BeginTransaction();
    }

    public void Dispose()
    {
        if (_transaction != null)
            _transaction.Rollback();
    }

    public void SaveChanges()
    {
        if (_transaction == null)
            throw new InvalidOperationException("UnitOfWork have already been saved.");

        _transaction.Commit();
        _transaction = null;
    }
}

在我的NHibernate存储库中,我有这个:

public class NHibernateRepository<TEntity, TKey> where TEntity : class
{
    ISession _session;
    protected Configuration config;
    protected ISessionFactory sessionFactory;

    public NHibernateRepository()
    {
        config = Fluently.Configure()
                  .Database(
                      MsSqlConfiguration
                      .MsSql2008
                      .ConnectionString(@"Data Source=localhost;Initial Catalog=mwms;Integrated Security=True;User ID=sa;Password=sql"))
                      .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHibernateRepository<TEntity, TKey>>())
                  .BuildConfiguration();

        sessionFactory = config.BuildSessionFactory();
        if (_session == null)
            _session = sessionFactory.OpenSession();
    }

    public NHibernateRepository(ISession session)
    {
        _session = session;
    }

    protected ISession Session
    {
        get {return _session;}
    }

    public void Create(TEntity entity)
    {
        NHibernateUnitOfWork unitOfWork = new NHibernateUnitOfWork(_session);
        _session.SaveOrUpdate(entity);
        unitOfWork.SaveChanges();
    }
}

我的代码总是会返回如下错误:

No persister for: Business.User

Business.User是在我的Nhibernate存储库中创建的实体。 我认为我遇到这个错误的原因是因为我使用工作单元的方式是错误的。我认为错误意味着事务未成功提交。 transaction.com将在我的工作单元中调用。

你能告诉我们如何在这里正确使用我的工作单位吗? 感谢..

0 个答案:

没有答案