public void IsInTransaction_Should_Return_False_When_No_Transaction_Exists() { var mockSession = MockRepository.GenerateStub <ISession>(); var unitOfWork = new NHUnitOfWork(mockSession); Assert.That(!unitOfWork.IsInTransaction); }
public void BasicTest() { var m = new Monkey(); m.Name = "George"; m.FlingsPoo = true; m.Bananas = new List <Banana>(); m.Bananas.Add(new Banana() { Color = "green" }); m.Bananas.Add(new Banana() { Color = "yellow" }); //Create new Monkey using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { uow.Save(m); } //Delete monkey using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { uow.Delete(m); } }
public void EmployeeProvideDataTest() { var uows = new MITD.Domain.Repository.UnitOfWorkScope( new Data.NH.NHUnitOfWorkFactory(() => PMSAdmin.Persistence.NH.PMSAdminSession.GetSession())); using (var uow = new NHUnitOfWork(PMSSession.GetSession())) using (var uow2 = uows.CurrentUnitOfWork) { var pmsAdminService = new PMS.ACL.PMSAdmin.PMSAdminService( new PMSAdmin.Application.UnitService(new PMSAdmin.Persistence.NH.UnitRepository(uows), new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)), new PMSAdmin.Application.JobService(new PMSAdmin.Persistence.NH.JobRepository(uows), new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)), new PMSAdmin.Application.CustomFieldService(new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)), new PMSAdmin.Application.JobPositionService(new PMSAdmin.Persistence.NH.JobPositionRepository(uows)), new PMSAdmin.Application.JobIndexService(new PMSAdmin.Persistence.NH.JobIndexRepository(uows), new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)) , new PMSAdmin.Application.UnitIndexService(new PMSAdmin.Persistence.NH.UnitIndexRepository(uows), new PMSAdmin.Persistence.NH.CustomFieldRepository(uows) )); var rep = new PMS.Persistence.NH.EmployeeRepository(uow); var provider = new PMS.Application.CalculationDataProvider(rep, pmsAdminService, new PMS.Persistence.NH.JobIndexPointRepository(uow)); var emp = rep.First(); MITD.PMSReport.Domain.Model.CalculationData empData; //var data = provider.Provide(emp, out empData); } }
static void Main(string[] args) { Account a = new Account("a", 100); WriteLine($"name:{a.Name},amount:{a.Balance}"); Account b = new Account("b", 100); WriteLine($"name:{a.Name},amount:{a.Balance}"); decimal amount = 50M; WriteLine($"a to b amount:{amount}"); IUnitOfWork nhUnitOfWork = new NHUnitOfWork(); IAccountRepository accountRepository = new AccountRepository(nhUnitOfWork); AccountService service = new AccountService(accountRepository, nhUnitOfWork); service.Transfer(a, b, amount); WriteLine("Transfered"); WriteLine($"name:{a.Name},amount:{a.Balance}"); WriteLine($"name:{a.Name},amount:{a.Balance}"); ReadKey(); }
public static LibraryService CreateLibraryService() { IUnitOfWork uow; IBookRepository bookRespository; IBookTitleRepository bookTitleRepository; IMemberRepository memberRespository; string persistenceStrategy = ConfigurationManager.AppSettings["PersistenceStrategy"]; if (persistenceStrategy == "EF") { uow = new EFUnitOfWork(); bookRespository = new BookRepository(uow); bookTitleRepository = new BookTitleRepository(uow); memberRespository = new MemberRepository(uow); } else { uow = new NHUnitOfWork(); bookRespository = new DataAccessLayerDemo.NHibernate.Repositories.BookRepository(uow); bookTitleRepository = new DataAccessLayerDemo.NHibernate.Repositories.BookTitleRepository(uow); memberRespository = new DataAccessLayerDemo.NHibernate.Repositories.MemberRepository(uow); } return(new LibraryService(uow, bookTitleRepository, bookRespository, memberRespository)); }
public WarehouseTest() { IUnitOfWork uow = new NHUnitOfWork(); this._warehouseRsponstroy = new WarehouseRepository(uow); AutoMapperBootStrapper.ConfigureAutoMapper(); }
public WorkflowActivityTests() { IUnitOfWork uow = new NHUnitOfWork(); this._workflowActivityNodeRepository = new WorkflowActivityNodeRepository(uow); this._workflowActivityRepository = new WorkflowActivityRepository(uow); }
private static void CreateAccount(int number, Instrument instrument) { using var uow = new NHUnitOfWork(); uow.OpenSession(_currentReadTenantIds); uow.BeginTransaction(); Console.WriteLine( $"Creating Account#: {number} under Instrument#: {instrument.Number} for Tenant ID: {_currentWriteTenantId}"); var account = new Account { AccountNumber = number, Instrument = instrument }; try { instrument.AddAccount(account); uow.Session.SaveOrUpdate(account); uow.Commit(); } catch (InvalidOperationException ex) { Console.WriteLine($"Unable to create Account: {ex.Message}"); uow.Rollback(); } }
public ProductTest() { IUnitOfWork uow = new NHUnitOfWork(); this._productRsponstroy = new ProductRepository(uow); AutoMapperBootStrapper.ConfigureAutoMapper(); }
public void TestDatapiontRepositoryFindByTEntityKeyMethod() { NHUnitOfWork nhUnitOfWork = new NHUnitOfWork(); DataPointRepository dataPointRepository = new DataPointRepository(nhUnitOfWork); DataPoint dataPoint = dataPointRepository.FindBy(14); }
public void TestDBPersistence() { var m = new Monkey(); m.Name = "George"; m.FlingsPoo = true; m.Bananas = new List <Banana>(); m.Bananas.Add(new Banana() { Color = "green" }); m.Bananas.Add(new Banana() { Color = "yellow" }); using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { uow.Save(m); } m.Name = "Rachael"; using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { uow.Save(m); } using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { uow.Delete(m); } }
public SupplierTests() { IUnitOfWork uow = new NHUnitOfWork(); this._supplierRepository = new SupplierRepository(uow); this._supplierProductRepository = new SupplierProductRepository(uow); }
public NHRepository(ISession session, ExceptionManager exManager, ILogger log) { this.session = session; this.exManager = exManager; this.log = log; this.sessionFactory = NHUnitOfWork.BuildSessionFactory(); }
public void NHUnitOfWorkDisposeSessionTest() { var input = new List<IMeasure> { new SimpleMeasure("ReteA", 10U) }; var loc = _entitiesFactory.CreateLocation("Location1", input); var uow = new NHUnitOfWork(_sessionFactory); uow.Dispose(); uow.Save(loc); }
public void EmployeeRepTest() { using (var uow = new NHUnitOfWork(PMSSession.GetSession())) { var rep = new EmployeeRepository(uow); var x = rep.GetPoints(rep.First(), new CalculationId(10)); } }
public RightsServiceTest() { IUnitOfWork uow = new NHUnitOfWork(); IRightsRepository _rightsRepository = new RightsRepository(uow); this._rightsService = new RightsService(_rightsRepository, uow); AutoMapperBootStrapper.ConfigureAutoMapper(); }
public PurchaseOrderTests() { IUnitOfWork uow = new NHUnitOfWork(); this._purchaseOrderRepoistroy = new PurchaseOrderRepository(uow); this._purchaseOrderDetailRepoistroy = new PurchaseOrderDetailRepository(uow); this._purchaseTypeRepoistroy = new PurchaseTypeRepository(uow); }
public ArrivalReceiptTests() { IUnitOfWork uow = new NHUnitOfWork(); this._arrivalReceiptRepository = new ArrivalReceiptRepository(uow); this._arrivalReceiptDetailRepository = new ArrivalReceiptDetailRepository(uow); this._arrivalNoticeDetailRepository = new ArrivalNoticeDetailRepository(uow); this._arrivalNoticeRepository = new ArrivalNoticeRepository(uow); }
public PaymentTests() { IUnitOfWork uow = new NHUnitOfWork(); this._paymentTypeRepository = new PaymentTypeRepository(uow); this._paymentTypeService = new PaymentTypeService(this._paymentTypeRepository, uow); this._paymentRepository = new PaymentRepository(uow); this._paymentService = new PaymentService(this._paymentRepository, uow); }
public ProjectTests() { IUnitOfWork uow = new NHUnitOfWork(); this._projectRepository = new ProjectRepository(uow); this._projectAttendanceRepository = new ProjectAttendanceRepository(uow); this._projectMaterialRepository = new ProjectMaterialRepository(uow); this._projectProductRepository = new ProjectProductRepository(uow); this._projectTypeRepository = new ProjectTypeRepository(uow); }
public InOutBoundTests() { IUnitOfWork uow = new NHUnitOfWork(); this._inOutBoundRepository = new InOutBoundRepository(uow); this._arrivalReceiptRepository = new ArrivalReceiptRepository(uow); this._arrivalReceiptDetailRepository = new ArrivalReceiptDetailRepository(uow); this._inOutReasonRepository = new InOutReasonRepository(uow); this._spotInventoryRepository = new SpotInventoryRepository(uow); }
public UsersServiceTest() { IUnitOfWork uow = new NHUnitOfWork(); IUsersRepository _usersRepository = new UsersRepository(uow); IOrganizationRepository _organizationRepository = new OrganizationRepository(uow); this._userService = new UsersService(_usersRepository, _organizationRepository, uow); this._organizationService = new OrganizationService(_organizationRepository, uow); AutoMapperBootStrapper.ConfigureAutoMapper(); }
public void AdvancedTest() { //Create new Monkey using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { var temp = new Monkey(); temp.Name = "George"; temp.FlingsPoo = true; temp.Bananas = new List <Banana>(); temp.Bananas.Add(new Banana() { Color = "green" }); temp.Bananas.Add(new Banana() { Color = "yellow" }); uow.Save(temp); } using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { Monkey temp = uow.Get <Monkey>(1); Assert.IsTrue(temp.Name == "George" && temp.Bananas[1].Color == "yellow"); } //Modify monkey using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { Monkey temp = uow.Get <Monkey>(1); temp.Name = "Bill"; uow.Save(temp); } using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { Monkey temp = uow.Get <Monkey>(1); Assert.IsTrue(temp.Name == "Bill"); } //Delete monkey using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { Monkey temp = uow.Get <Monkey>(1); uow.Delete(temp); } using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr)) { Monkey temp = uow.Get <Monkey>(1); Assert.IsNull(temp); } }
public void BeginTransaction_Throws_InvalidOperationException_When_Transaction_Already_Running() { var mockSession = MockRepository.GenerateStub<ISession>(); mockSession.Stub(x => x.BeginTransaction(IsolationLevel.Unspecified)) .IgnoreArguments().Return(MockRepository.GenerateStub<global::NHibernate.ITransaction>()); var unitOfWork = new NHUnitOfWork(mockSession); unitOfWork.BeginTransaction(); Assert.That(unitOfWork.IsInTransaction); Assert.Throws<InvalidOperationException>(() => unitOfWork.BeginTransaction()); }
public MapaController() { var unitOfWorkRepository = new NHUnitOfWorkRepository <Mapa>(); var unitOfWork = new NHUnitOfWork <Mapa>(unitOfWorkRepository); var mapaRepository = new MapaRepository(unitOfWork); this._mapaServices = new MapaServices(mapaRepository); var fileRepostory = new MapaFileRepository(); this._fileServices = new FileServices(fileRepostory); }
public void LogServiceTest() { //LocatorCreator.Execute(); var container = new WindsorContainer(); container.Register(Component.For <ILoggerService>().ImplementedBy <DbLoggerService>().LifeStyle.BoundTo <IService>()); //container.Register(Component.For<ILogRepository>().ImplementedBy<LogRepository>().LifeStyle.Transient); container.Register(Component.For <IConnectionProvider>() .UsingFactoryMethod(c => new ConnectionProvider(() => { var s = System.Configuration.ConfigurationManager. ConnectionStrings["PMSDBConnection"].ConnectionString; var res = new SqlConnection(s); res.Open(); return(res); })).LifestyleBoundTo <IService>()); DataAccessConfigHelper.ConfigureContainer <UserRepository>(container, () => { var session = PMSSecuritySession.GetSession(container.Resolve <IConnectionProvider>().GetConnection()); return(session); }, "PMSSecurity"); var locator = new WindsorServiceLocator(container); ServiceLocator.SetLocatorProvider(() => locator); //var userRep = ServiceLocator.Current.GetInstance<UserRepository>(); var uows = new MITD.Domain.Repository.UnitOfWorkScope( new Data.NH.NHUnitOfWorkFactory(() => PMSSecurity.Persistence.NH.PMSSecuritySession.GetSession())); using (var uow = new NHUnitOfWork(PMSSession.GetSession())) using (var uow2 = uows.CurrentUnitOfWork) { var logFactory = new LoggerServiceFactory(); var logManager = new LogManagerService(logFactory); var logService = new LogService(logManager); var gid = Guid.NewGuid(); Log log = new EventLog(new LogId(gid), "diddd", LogLevel.Information, null, "clll", "mett", "ttttt", "mmmmmmm"); logService.AddEventLog(log.Code, log.LogLevel, null, log.ClassName, log.MethodName, log.Title, log.Messages); } }
public void Flush_Calls_Underlying_ISession_Flush() { var mockSession = MockRepository.GenerateMock <ISession>(); mockSession.Expect(x => x.Flush()); var unitOfWork = new NHUnitOfWork(mockSession); unitOfWork.Flush(); mockSession.VerifyAllExpectations(); }
public static void ReloadData() { var session = CurrencyAndMeasurementSession.GetSession(); var uow = new NHUnitOfWork(session); var transaction = new NHTransactionHandler(); var configurator = new AggregateRootConfigurator(new TIBA.Core.EventPublisher()); //create an uomType before create uom var nhExMap = new NHRepositoryExceptionMapper(new List<System.Tuple<DBActionType, string, Exception>>()); var target = new UnitOfMeasureRepository(transaction, uow, nhExMap, configurator); UnitOfMeasureParserHelper.RegisterParsersFromRepository(target); }
private void initialized() { using (var uow = new NHUnitOfWork(PMSSession.GetSession())) { var periodRep = new PeriodRepository(uow); for (int i = 0; i < 5; i++) { var period = new Period(new PeriodId(periodRep.GetNextId()), "Test", DateTime.Now, DateTime.Now, 91); periodRep.Add(period); } uow.Commit(); } }
public void can_create_payroll_of_active_employees() { using (var uow = new NHUnitOfWork()) { var ees = _employees.FetchAllActive(); var actual = ees.Count; var pr = PayrollReport.Create(ees, Date.Now); EventBroker.getInstance().Command(new CommandIncludeSalaryDeductionInReport(pr)); Assert.True(ees.Count > 0); Assert.Equal(pr.Records.Count, actual); _payrolls.Save(pr); uow.Commit(); } }
public void BeginTransaction_Throws_InvalidOperationException_When_Transaction_Already_Running() { var mockSession = MockRepository.GenerateStub <ISession>(); mockSession.Stub(x => x.BeginTransaction(IsolationLevel.Unspecified)) .IgnoreArguments().Return(MockRepository.GenerateStub <global::NHibernate.ITransaction>()); var unitOfWork = new NHUnitOfWork(mockSession); unitOfWork.BeginTransaction(); Assert.That(unitOfWork.IsInTransaction); Assert.Throws <InvalidOperationException>(() => unitOfWork.BeginTransaction()); }
public SupplierTests() { AutoMapperBootStrapper.ConfigureAutoMapper(); IUnitOfWork uow = new NHUnitOfWork(); this._supplierProductRepository = new SupplierProductRepository(uow); this._supplierProductService = new SupplierProductService(this._supplierProductRepository, uow); this._usersRepository = new UsersRepository(uow); this._productRepository = new ProductRepository(uow); this._supplierRepository = new SupplierRepository(uow); this._supplierService = new SupplierService(this._supplierRepository, this._usersRepository, this._productRepository, uow); }
public InOutBoundTest() { IUnitOfWork uow = new NHUnitOfWork(); this._outBoundRsponstroy = new OutBoundRepository(uow); this._inBoundRsponstroy = new InBoundRepository(uow); this._inOutBoundRsponstroy = new InOutBoundRepository(uow); this._productRepository = new ProductRepository(uow); this._warehouseRepository = new WarehouseRepository(uow); this._warehouseShelfRepository = new WarehouseShelfRepository(uow); this._inOutBoundService = new InOutBoundService(_inOutBoundRsponstroy, _outBoundRsponstroy, _inBoundRsponstroy, _productRepository, _warehouseRepository, _warehouseShelfRepository, uow); AutoMapperBootStrapper.ConfigureAutoMapper(); }
public void Begin_Transaction_Should_Start_A_New_Transaction_With_Default_IsolationLevel() { var mockSession = MockRepository.GenerateMock<ISession>(); var mockTransaction = MockRepository.GenerateStub<global::NHibernate.ITransaction>(); mockSession.Expect(x => x.BeginTransaction(IsolationLevel.ReadCommitted)) .Return(mockTransaction); var unitOfWork = new NHUnitOfWork(mockSession); Assert.That(!unitOfWork.IsInTransaction); unitOfWork.BeginTransaction(); Assert.That(unitOfWork.IsInTransaction); mockSession.VerifyAllExpectations(); }
public void GetSessionFor_returns_different_session_for_types_handled_by_different_factory() { var resolver = new Mock<INHSessionResolver>(); resolver.Setup(x => x.GetSessionKeyFor<string>()).Returns(Guid.NewGuid()); resolver.Setup(x => x.GetSessionKeyFor<int>()).Returns(Guid.NewGuid()); resolver.Setup(x => x.OpenSessionFor<string>()).Returns(new Mock<ISession>().Object); resolver.Setup(x => x.OpenSessionFor<int>()).Returns(new Mock<ISession>().Object); var unitOfWork = new NHUnitOfWork(resolver.Object); var stringSession = unitOfWork.GetSession<string>(); var intSession = unitOfWork.GetSession<int>(); Assert.AreNotSame(stringSession, intSession); resolver.Verify(x => x.GetSessionKeyFor<string>()); resolver.Verify(x => x.GetSessionKeyFor<int>()); resolver.Verify(x => x.OpenSessionFor<string>()); resolver.Verify(x => x.OpenSessionFor<int>()); }
public void Flush_calls_flush_on_all_open_ISession_instances() { var resolver = new Mock<INHSessionResolver>(); resolver.Setup(x => x.GetSessionKeyFor<string>()).Returns(Guid.NewGuid()); resolver.Setup(x => x.GetSessionKeyFor<int>()).Returns(Guid.NewGuid()); var session = new Mock<ISession>(); resolver.Setup(x => x.OpenSessionFor<string>()).Returns(session.Object); resolver.Setup(x => x.OpenSessionFor<int>()).Returns(session.Object); var unitOfWork = new NHUnitOfWork(resolver.Object); unitOfWork.GetSession<string>(); unitOfWork.GetSession<int>(); unitOfWork.Flush(); resolver.Object.OpenSessionFor<string>(); session.Verify(x => x.Flush()); resolver.Object.OpenSessionFor<int>(); session.Verify(x => x.Flush()); }
public void GetSessionFor_returns_session_for_type() { var resolver = new Mock<INHSessionResolver>(); resolver.Setup(x => x.GetSessionKeyFor<string>()).Returns(Guid.NewGuid()); resolver.Setup(x => x.OpenSessionFor<string>()).Returns(new Mock<ISession>().Object); var unitOfWork = new NHUnitOfWork(resolver.Object); var session = unitOfWork.GetSession<string>(); Assert.IsNotNull(session); }
public void Flush_Calls_Underlying_ISession_Flush() { var mockSession = MockRepository.GenerateMock<ISession>(); mockSession.Expect(x => x.Flush()); var unitOfWork = new NHUnitOfWork(mockSession); unitOfWork.Flush(); mockSession.VerifyAllExpectations(); }
public void IsInTransaction_Should_Return_False_When_No_Transaction_Exists() { var mockSession = MockRepository.GenerateStub<ISession>(); var unitOfWork = new NHUnitOfWork(mockSession); Assert.That(!unitOfWork.IsInTransaction); }
public void TransactionalFlush_Rollsback_Transaction_When_Flush_Throws_Exception() { var mockSession = MockRepository.GenerateMock<ISession>(); var mockTransaction = MockRepository.GenerateMock<global::NHibernate.ITransaction>(); mockSession.Expect(x => x.BeginTransaction(IsolationLevel.ReadCommitted)) .Return(mockTransaction); mockSession.Expect(x => x.Flush()).Throw(new Exception()); mockTransaction.Expect(x => x.Rollback()); var unitOfWork = new NHUnitOfWork(mockSession); Assert.Throws<Exception>(unitOfWork.TransactionalFlush); mockSession.VerifyAllExpectations(); mockTransaction.VerifyAllExpectations(); }
public void TransactionalFlush_Starts_A_Transaction_With_Specified_IsolationLevel_And_Commits_When_Flush_Succeeds() { var mockSession = MockRepository.GenerateMock<ISession>(); var mockTransaction = MockRepository.GenerateMock<global::NHibernate.ITransaction>(); mockSession.Expect(x => x.BeginTransaction(IsolationLevel.ReadUncommitted)) .Return(mockTransaction); mockSession.Expect(x => x.Flush()); mockTransaction.Expect(x => x.Commit()); var unitOfWork = new NHUnitOfWork(mockSession); unitOfWork.TransactionalFlush(IsolationLevel.ReadUncommitted); mockSession.VerifyAllExpectations(); mockTransaction.VerifyAllExpectations(); }
public void TransactionalFlush_Uses_Existing_Transaction_When_Transactional_AlreadyRunning() { var mockSession = MockRepository.GenerateMock<ISession>(); var mockTransaction = MockRepository.GenerateMock<global::NHibernate.ITransaction>(); mockSession.Expect(x => x.BeginTransaction(IsolationLevel.ReadCommitted)) .Return(mockTransaction) .Repeat.Once(); //Expect BeginTransaction to be called only once. var unitOfWork = new NHUnitOfWork(mockSession); unitOfWork.BeginTransaction(); unitOfWork.TransactionalFlush(); mockSession.VerifyAllExpectations(); mockTransaction.VerifyAllExpectations(); }
public void NHUnitOfWorkOperationsTest() { //CREATE = SAVE AND COMMIT using (var uow = new NHUnitOfWork(_sessionFactory)) { // populate the database var input = new List<IMeasure> { new SimpleMeasure("ReteA", 10U) }; var loc = _entitiesFactory.CreateLocation("Location1", input); loc.TotalTime = TimeVal; var input2 = new List<IMeasure> { new SimpleMeasure("ReteB", 50U), new SimpleMeasure("ReteC", 100U) }; var loc2 = _entitiesFactory.CreateLocation("Location2", input2); loc2.TotalTime = TimeVal1; //this saves everything else via cascading uow.Save(loc); uow.Save(loc2); uow.Commit(); } // READ = // Get, GetLocationByName and GetAll using (var uow = new NHUnitOfWork(_sessionFactory)) { var locA = uow.GetLocationByName("Location1"); Assert.AreEqual(locA.Name, "Location1"); Assert.AreEqual(locA.TotalTime, TimeVal); var locB = uow.Get<Location>(locA.Id); Assert.AreEqual(locB.Name, "Location1"); Assert.AreEqual(locB.TotalTime, TimeVal); IList<Location> locations = uow.GetAll<Location>(); Assert.AreEqual(locations.Count, 2); foreach (var location in locations) { //For a visual feedback Console.WriteLine(location.ToString()); if (location.Name == "Location1") { Assert.AreEqual(location.TotalTime, TimeVal); } else if (location.Name == "Location2") { Assert.AreEqual(location.TotalTime, TimeVal1); } else { Log.Debug(location.Name); Assert.Fail("Location name not matching"); } } var networks = uow.GetAll<Network>(); Assert.AreEqual(networks.Count, 3); uow.Commit(); } Location longLivedLocation; const string locName = "Location1"; // UPDATE = SAVE AND COMMIT // update within a single unit of work using (var uow = new NHUnitOfWork(_sessionFactory)) { longLivedLocation = uow.GetLocationByName(locName); longLivedLocation.TotalTime = TimeVal2; uow.Commit(); } using (var uow = new NHUnitOfWork(_sessionFactory)) { var locB = uow.Get<Location>(longLivedLocation.Id); Assert.AreEqual(locB.TotalTime, TimeVal2); } // update of an entity retrieved in a unit of work // BEWARE OF DIRTY WRITES!!! THEY ARE STILL DIFFERENT TRANSACTIONS!!! using (var uow = new NHUnitOfWork(_sessionFactory)) { longLivedLocation.TotalTime = TimeVal3; uow.Save(longLivedLocation); uow.Commit(); } using (var uow = new NHUnitOfWork(_sessionFactory)) { var tmp = uow.GetLocationByName(locName); Assert.AreEqual(tmp.TotalTime, TimeVal3); uow.Commit(); } // ROLLBACK using (var uow = new NHUnitOfWork(_sessionFactory)) { longLivedLocation = uow.GetLocationByName("Location1"); longLivedLocation.TotalTime = TimeVal4; var input = new List<IMeasure> { new SimpleMeasure("ReteC", 10U) }; var loc = _entitiesFactory.CreateLocation("Location3", input); loc.TotalTime = TimeVal; uow.Save(loc); uow.Rollback(); } using (var uow = new NHUnitOfWork(_sessionFactory)) { var locB = uow.Get<Location>(longLivedLocation.Id); //old value Assert.AreEqual(locB.TotalTime, TimeVal3); var locations = uow.GetAll<Location>(); Assert.AreEqual(locations.Count, 2); foreach (var location in locations) { if(location.Name!="Location1" && location.Name!="Location2") { Log.Debug(location.Name); Assert.Fail("Location added in rollbacked unit of work"); } } } // LAZY LOADING // It seems it does not work (always eager loading). Less performances, zero problems... // Check it by hand, looking at logs Log.Debug("LAZY LOADING"); Location locLazy; using (var uow = new NHUnitOfWork(_sessionFactory)) { locLazy = uow.GetLocationByName("Location1"); } Assert.AreEqual(locLazy.Name, "Location1"); Assert.AreEqual(locLazy.TotalTime, TimeVal3); var up = new List<IMeasure> { new SimpleMeasure("ReteA", 20U) }; locLazy.UpdateStats(up); Log.Debug(locLazy.ToString()); IList<Location> locLazies; using (var uow = new NHUnitOfWork(_sessionFactory)) { locLazies = uow.GetAll<Location>(); } up = new List<IMeasure> { new SimpleMeasure("ReteA", 10U), new SimpleMeasure("ReteB", 40U) }; locLazies[1].UpdateStats(up); Log.Debug(locLazies[1].ToString()); // DELETE using (var uow = new NHUnitOfWork(_sessionFactory)) { var locations = uow.GetAll<Location>(); foreach (var location in locations) { uow.Delete(location); } uow.Commit(); } // check deletion cascade using (var uow = new NHUnitOfWork(_sessionFactory)) { var locations = uow.GetAll<Location>(); Assert.AreEqual(locations.Count, 0); var networks = uow.GetAll<Network>(); Assert.AreEqual(networks.Count, 0); } }
public void Comitting_Transaction_Releases_Transaction_From_UnitOfWork() { var mockSession = MockRepository.GenerateMock<ISession>(); mockSession.Expect(x => x.BeginTransaction(IsolationLevel.ReadCommitted)) .Return(MockRepository.GenerateStub<global::NHibernate.ITransaction>()); var unitOfWork = new NHUnitOfWork(mockSession); var transaction = unitOfWork.BeginTransaction(); Assert.That(unitOfWork.IsInTransaction); transaction.Commit(); Assert.That(!unitOfWork.IsInTransaction); mockSession.VerifyAllExpectations(); }
public void Dispose_UnitOfWork_Disposed_Underlying_Transaction_And_Session() { var mockSession = MockRepository.GenerateMock<ISession>(); var mockTransaction = MockRepository.GenerateMock<global::NHibernate.ITransaction>(); mockSession.Expect(x => x.BeginTransaction(IsolationLevel.ReadCommitted)) .Return(mockTransaction); mockTransaction.Expect(x => x.Dispose()); mockSession.Expect(x => x.Dispose()); using (var unitOfWork = new NHUnitOfWork(mockSession)) { unitOfWork.BeginTransaction(); } mockSession.VerifyAllExpectations(); mockTransaction.VerifyAllExpectations(); }
public void NHUnitOfWorkDisposeTransactionTest() { var uow = new NHUnitOfWork(_sessionFactory); uow.Dispose(); uow.Commit(); }