Example #1
1
        /// <summary>
        /// Dient eenmalig uitgevoerd te worden
        /// </summary>
        private void InitializeTiles(ISessionFactory factory)
        {
            Random random = new Random();
            int result = 0;
            var nhSession = factory.OpenSession();

            MapTiles = nhSession.QueryOver<MapTile>().List();
            if (MapTiles.IsEmpty())
            {
                MapTiles = new List<MapTile>();
                using (var transaction = nhSession.BeginTransaction())
                {
                    for (int x = 0; x < 8; x++)
                    {
                        for (int y = 0; y < 8; y++)
                        {
                            result = random.Next(0, 10);
                            var tile = new MapTile() {Name = "Wasteland", X = x, Y = y};
                            MapTiles.Add(tile);
                            nhSession.Save(tile);
                        }
                    }

                    transaction.Commit();
                }
            }
        }
			public FullInitializedRetrievedEntity(ISessionFactory factory)
			{
				this.factory = factory;
				object savedId;
				using (var session = factory.OpenSession())
				using (session.BeginTransaction())
				{
					var entity = new MyClass();
					entity.Children.Add(new MyChild { Parent = entity });
					entity.Components.Add(new MyComponent { Something = "something" });
					entity.Elements.Add("somethingelse");
					savedId = session.Save(entity);
					session.Transaction.Commit();
				}

				using (var session = factory.OpenSession())
				using (session.BeginTransaction())
				{
					entity = session.Get<MyClass>(savedId);
					NHibernateUtil.Initialize(entity.Children);
					NHibernateUtil.Initialize(entity.Components);
					NHibernateUtil.Initialize(entity.Elements);
					session.Transaction.Commit();
				}
			}
        public void CanReadAndSavePerson()
        {
            factory = new SessionProvider().Factory;
            int personId;
			using (var session = factory.OpenSession())
			{
				using (var transaction = session.BeginTransaction())
				{
					var person = new Person { Name = new Name { First = "Olo", Last = "Bolus" } };
					var cat = new Cat { Name = "Filip" };
					session.Save(cat);
					session.Save(person);
					transaction.Commit();
					personId = person.Id;
				}
			}
            using (var session = factory.OpenSession())
            {
                using (session.BeginTransaction())
                {
                    var person = (from p in ((IOrderedQueryable<Person>)session.Linq<Person>()) where p.Id == personId select  p).First()  ;
                    Assert.That(person.Name.First,Is.EqualTo("Olo"));
                }
            }
        }
Example #4
0
        private ISession getExistingOrNewSession(ISessionFactory factory)
        {
            if (HttpContext.Current != null)
            {
                ISession session = GetExistingWebSession();
                if (session == null)
                {
                    session = openSessionAndAddToContext(factory);
                }
                else if (!session.IsOpen)
                {
                    session = openSessionAndAddToContext(factory);
                }

                return session;
            }

            if (_currentSession == null)
            {
                _currentSession = factory.OpenSession();
            }
            else if (!_currentSession.IsOpen)
            {
                _currentSession = factory.OpenSession();
            }

            return _currentSession;
        }
        public static void Run(ISessionFactory factory)
        {
            int bobId;

            // Save a Customer
            using (ISession session = factory.OpenSession())
            {
                Customer bob = ObjectMother.Customer();

                Print("Saving Customer...");

                session.Save(bob);
                session.Flush();

                bobId = bob.CustomerID;
            }

            // Load it back up and print out the details
            using (ISession session = factory.OpenSession())
            {
                Print("Loading Customer");
                Customer bob = session.Load<Customer>(bobId);

                Print("{0}", bob);

                Print("Loading Customer (again, but should be a cache hit)");

                // Load it again, 1st level cache
                bob = session.Load<Customer>(bobId);

                Print("{0}", bob);

                Print("Delete the Customer");
                session.Delete(bob);
                session.Flush();
            }

            // Verify it was deleted
            using (ISession session = factory.OpenSession())
            {
                Print("Try to load it again");

                try
                {
                    Customer bob = session.Load<Customer>(bobId);
                    Print("This should not execute! {0}", bob);
                }
                catch( ObjectNotFoundException )
                {
                    Print("Customer 'Bob' was successfully deleted");
                }
            }
        }
        private ISession GetExistingOrNewSession(ISessionFactory factory)
        {
            if (_currentSession == null)
            {
                _currentSession = factory.OpenSession();
            }
            else if (!_currentSession.IsOpen)
            {
                _currentSession = factory.OpenSession();
            }

            return _currentSession;
        }
        public static void Run(ISessionFactory factory)
        {
            int customerId;

            // Save a customer with a bunch of orders
            using (ISession session = factory.OpenSession())
            {
                var customer = ObjectMother.Customer();

                for( var i = 0; i < 5; i++ )
                {
                    var order = ObjectMother.Order()
                        .Customer(customer)
                        .Amount(100 + i)
                        .Product("Product " + i)
                        .Quantity(10 + i)
                        .Date( (i+1) + "/1/2008");

                    customer.Orders.Add(order);
                }

                Print("Saving 1 Customer + 5 Orders...");

                session.Save(customer);
                session.Flush();

                customerId = customer.CustomerID;
            }

            // Load the customer back up, lazy load the orders
            using( ISession session = factory.OpenSession() )
            {
                Print("Loading customer...");

                var customer = session.Load<Customer>(customerId);

                Print(customer.ToString());

                Print("Loading the orders...");
                
                foreach( var order in customer.Orders )
                {
                    Print("Order {0}: Amount: {1}", order.OrderID, order.Amount);
                }

                Print("Deleting the customer (should delete orders too!)");

                session.Delete(customer);
                session.Flush();
            }
        }
        public InMemoryNHibernateSessionSource(IEnumerable<Assembly> mappingAssemblies)
        {
            var configuration = new Configuration();
            configuration.DataBaseIntegration(cfg =>
                                              {
                                                  cfg.ConnectionString = "FullUri=file:memorydb.db?mode=memory&cache=shared";
                                                  cfg.Driver<SQLite20Driver>();
                                                  cfg.Dialect<SQLiteDialect>();
                                                  cfg.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                                                  cfg.SchemaAction = SchemaAutoAction.Update;
                                              });

            configuration.AddCodeMappingsFromAssemblies(mappingAssemblies);

            SchemaMetadataUpdater.QuoteTableAndColumns(configuration);

            _factory = configuration.BuildSessionFactory();

            _connectionCreatingSessionThatShouldNotBeDisposedUntilTestHasRunToEnd = _factory.OpenSession();
            _connection = _connectionCreatingSessionThatShouldNotBeDisposedUntilTestHasRunToEnd.Connection;

            new SchemaExport(configuration).Execute(
                              script: false,
                              export: true,
                              justDrop: false,
                              connection: _connection,
                              exportOutput: null);
        }
        public void OnStartUp()
        {
            SetRootPathProject();

            XmlTextReader configReader = new XmlTextReader(new MemoryStream(NHibernate.Test.Properties.Resources.Configuration));
            DirectoryInfo dir = new DirectoryInfo(this.rootPathProject + ".Hbm");
            Console.WriteLine(dir);

            builder = new NhConfigurationBuilder(configReader, dir);

            builder.SetProperty("connection.connection_string", GetConnectionString());

            try
            {
                builder.BuildSessionFactory();
                sessionFactory = builder.SessionFactory;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
            
            sessionProvider = new SessionManager(sessionFactory);
            currentPagedDAO = new EnterprisePagedDAO(sessionProvider);
            currentRootPagedDAO = new EnterpriseRootDAO<object>(sessionProvider);
            currentSession = sessionFactory.OpenSession();
        }
 private NHibernateHelper()
 {
     Configuration cfg = new Configuration();
     cfg.AddAssembly("DataModels");
     sessionFactory = cfg.BuildSessionFactory();
     session = sessionFactory.OpenSession();
 }
Example #11
0
 private void loadArticulo(ISessionFactory sessionFactory)
 {
     using(ISession session = sessionFactory.OpenSession()){
         Articulo articulo=(Articulo)session.Load (typeof(Articulo),2L);
         Console.WriteLine("Articulo ID={0} Nombre={1} Precio={2} Categoria={3}",articulo.Id,articulo.Nombre, articulo.Precio,articulo.Categoria.Nombre);
     }
 }
        public SetModificationDateIntegrationTests()
        {
            listener =	new SetModificationTimeFlushEntityEventListener()
                {
                    CurrentDateTimeProvider = () => defaultDate
                };

            Configuration config = null;
            sessionFactory = Fluently.Configure()
                .Database(SQLiteConfiguration.Standard.InMemory)
                .Mappings(m =>
                {
                    m.FluentMappings.Add<ThingMap>();
                    m.FluentMappings.Add<InheritedThingMap>();
                    m.FluentMappings.Add<RelatedThingMap>();
                })
                .ExposeConfiguration(cfg =>
                {
                    listener.Register(cfg);
                    config = cfg;
                })
                .BuildSessionFactory();

            session = sessionFactory.OpenSession();

            using (var tx = session.BeginTransaction())
            {
                new SchemaExport(config).Execute(false, true, false, session.Connection, null);
                tx.Commit();
            }

            session.BeginTransaction();
        }
 private static void GenerateData(ISessionFactory factory, Type entityClass, IGeometryCreator creator)
 {
     using (ISession session = factory.OpenSession())
     {
         using (ITransaction tx = session.BeginTransaction())
         {
             try
             {
                 for (int i = 0; i < GeneratedRowsPerEntityCount; i++)
                 {
                     IGeometry geom = creator.Create();
                     geom.SRID = 4326;
                     object entity = Activator.CreateInstance(entityClass, i, "feature " + i, geom);
                     session.Save(entity);
                 }
             }
             catch (Exception e)
             {
                 throw new ApplicationException("Failed loading data of type "
                         + entityClass.Name, e);
             }
             tx.Commit();
         }
     }
 }
        public void Setup() {
            _databaseFileName = Path.GetTempFileName();
            _sessionFactory = DataUtility.CreateSessionFactory(_databaseFileName);

            _tempFolder = Path.GetTempFileName();
            File.Delete(_tempFolder);
            var appDataFolder = AppDataFolderTests.CreateAppDataFolder(_tempFolder);

            var builder = new ContainerBuilder();

            _session = _sessionFactory.OpenSession();
            builder.RegisterInstance(appDataFolder).As<IAppDataFolder>();
            builder.RegisterType<SqlCeDataServicesProvider>().As<IDataServicesProvider>();
            builder.RegisterType<DataServicesProviderFactory>().As<IDataServicesProviderFactory>();
            builder.RegisterType<StubReportsCoordinator>().As<IReportsCoordinator>();
            builder.RegisterType<DefaultDataMigrationInterpreter>().As<IDataMigrationInterpreter>();
            builder.RegisterType<SqlCeCommandInterpreter>().As<ICommandInterpreter>();
            builder.RegisterType<SessionConfigurationCache>().As<ISessionConfigurationCache>();
            builder.RegisterType<SessionFactoryHolder>().As<ISessionFactoryHolder>();
            builder.RegisterType<DefaultDatabaseCacheConfiguration>().As<IDatabaseCacheConfiguration>();
            builder.RegisterType<StubHostEnvironment>().As<IHostEnvironment>();
            builder.RegisterInstance(new TestTransactionManager(_session)).As<ITransactionManager>();
            builder.RegisterInstance(new ShellBlueprint { Records = Enumerable.Empty<RecordBlueprint>() }).As<ShellBlueprint>();
            builder.RegisterInstance(new ShellSettings { Name = "temp", DataProvider = "SqlCe", DataTablePrefix = "TEST" }).As<ShellSettings>();
            builder.RegisterModule(new DataModule());
            _container = builder.Build();

            _interpreter = _container.Resolve<IDataMigrationInterpreter>() as DefaultDataMigrationInterpreter;
            _schemaBuilder = new SchemaBuilder(_interpreter);
        }
 public UnitOfWork(ISessionFactory sessionFactory)
 {
     _sessionFactory = sessionFactory;
     Session = _sessionFactory.OpenSession();
     Session.FlushMode = FlushMode.Auto;
     _transaction = Session.BeginTransaction(IsolationLevel.ReadCommitted);
 }
        public NHibernateEventStoreTransaction(ISessionFactory sf)
        {
            this.SessionFactory = sf;
            this.Session = sf.OpenSession();

            WebSessionContext.Bind(this.Session);;
        }
Example #17
0
        public static void UseNHibernate(this AppConfigurator configurator, ISessionFactory sessionFactory)
        {
            var runtime = configurator.AppRuntime;

            runtime.Container.Register<IDomainDbSession>(_ => new NhDomainDbSession(sessionFactory.OpenSession()));
            runtime.Container.Register<IDomainRepository>(_ => new NhDomainRepository(_.Resolve<IDomainDbSession>(), _.Resolve<IRelayWorker>()));
        }
        public ISessionFactory Seed(ISessionFactory factory)
        {
            var users = new[]
                       {
                           new User {Name = "Joe"},
                           new User {Name = "Anne"},
                           new User {Name = "Admin"}
                       };

            using (var s = factory.OpenSession())
            {
                if (!s.Query<IUser>().Any())
                {
                    using (var t = s.BeginTransaction())
                    {
                        users.ForEach(u =>
                                          {
                                              s.Save(u);

                                              s.Save(CreateBragForUser(u));
                                          });

                        t.Commit();
                    }
                }
            }

            return factory;
        }
Example #19
0
        private bool disposed; // Necessary for IDisposable

        #endregion Fields

        #region Constructors

        public UnitOfWork(ISessionFactory sessionFactory)
        {
            this.sessionFactory = sessionFactory;
            this.Session = sessionFactory.OpenSession();
            this.Session.FlushMode = FlushMode.Auto;
            this.transaction = this.Session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
        }
        protected DatabaseFixture()
        {
            BeforeSetup();

            SillyContainer.SessionProvider = (() => session);
            var sillyContainer = new SillyContainer();
            ServiceLocator.SetLocatorProvider(() => sillyContainer);

            var cfg = new Configuration()
                .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
                .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)
                .SetProperty(Environment.ConnectionString, ConnectionString)
                .SetProperty(Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName)
                .SetProperty(Environment.ReleaseConnections, "on_close")
                .SetProperty(Environment.UseSecondLevelCache, "true")
                .SetProperty(Environment.UseQueryCache, "true")
                .SetProperty(Environment.CacheProvider,typeof(HashtableCacheProvider).AssemblyQualifiedName)
                .AddAssembly(typeof (User).Assembly);

            Security.Configure<User>(cfg, SecurityTableStructure.Prefix);

            factory = cfg.BuildSessionFactory();

            session = factory.OpenSession();

            new SchemaExport(cfg).Execute(false, true, false, session.Connection, null);

            session.BeginTransaction();

            SetupEntities();
        }
Example #21
0
        public SqlLiteBuilder()
        {
            var showSql = GetShowSql();

            var configuration = new Configuration()
                .Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>())
                .DataBaseIntegration(db =>
                {
                    db.Dialect<SQLiteDialect>();
                    db.Driver<SQLite20Driver>();
                    db.ConnectionString = "data source=:memory:";
                })
                .SetProperty(Environment.ReleaseConnections, "on_close")
                .SetProperty(Environment.ShowSql, showSql)
                .AddAssembly(Assembly.GetCallingAssembly());

            _sessionFactory = Fluently.Configure(configuration)
                .Mappings(mappings => mappings.FluentMappings.AddFromAssemblyOf<SqlLiteBuilder>())
                .BuildSessionFactory();

            _session = _sessionFactory.OpenSession();

            var textWriter = GetTextWriter();

            var schemaExport = new SchemaExport(configuration);

            schemaExport.Execute(false, true, false, _session.Connection, textWriter);
        }
        private static void SavePostsWithHilo(ISessionFactory sessionFactory, int number)
        {
            using (var session = sessionFactory.OpenSession())
            using (var tx = session.BeginTransaction())
            {
                Console.WriteLine("Press any key to save some posts to the database");
                Console.ReadLine();

                for (var i = 0; i < number; i++)
                {
                    var post = new PostWithHilo
                    {
                        Description = "NH vs EF",
                        Message = "Wow, NHibernate is so much cooler than the Entity Framework",
                        PostedOn = DateTime.Now
                    };

                    session.Save(post);
                }

                tx.Commit();

                Console.WriteLine("Posts saved");
            }
        }
Example #23
0
			public MapScenario(ISessionFactory factory)
			{
				this.factory = factory;
				using (ISession s = factory.OpenSession())
				{
					using (ITransaction t = s.BeginTransaction())
					{
						var entity = new Base();
						entity.NamedChildren = new Dictionary<string, Child>
						                       {
						                       	{"Child1", new Child()},
						                       	{"NullChild", null},
						                       };

                        var child1 = new AnotherChild { Name = "AnotherChild1" };
                        var child2 = new AnotherChild { Name = "AnotherChild2" };

					    s.Save(child1);
					    s.Save(child2);

                        entity.OneToManyNamedChildren = new Dictionary<string, AnotherChild> 
                                               {
                                                {"AnotherChild1" , child1}, 
                                                {"AnotherChild2" , child2} 
                                               };

						s.Save(entity);
						t.Commit();
					}
				}
			}
Example #24
0
 /// <summary>
 /// Create a customer factory based on the configuration given in the configuration file
 /// </summary>
 public OrderDetailsFactory()
 {
     config = new Configuration();
     config.AddAssembly("nhibernator");
     factory = config.BuildSessionFactory();
     session = factory.OpenSession();
 }
 public virtual ISession CreateSession(ISessionFactory sessionFactory)
 {
     var nhi = new NHInterceptor(interceptor, notifier);
     var s = sessionFactory.OpenSession(nhi);
     nhi.Session = s;
     return s;
 }
        public Form1()
        {
            //Type t = typeof(User);
            //Type t1 = typeof(Course<>);
            //Type t2 = typeof(Course<Teacher>);
            //Type t3 = typeof(Course<Collaborator>);

            //Console.WriteLine(t.Name);
            //Console.WriteLine(t1.Name);
            //Console.WriteLine(t2.Name);
            //Console.WriteLine(t3.Name);

            InitializeComponent();
            SetRootPathProject();

            XmlTextReader configReader = new XmlTextReader(new MemoryStream(WFA_NHibernate.Properties.Resources.Configuration));
            DirectoryInfo dir = new DirectoryInfo(this.rootPathProject + "MappingsXml");
            builder = new NhConfigurationBuilder(configReader, dir);

            builder.SetProperty("connection.connection_string", GetConnectionString());

            builder.BuildSessionFactory();
            sessionFactory = builder.SessionFactory;

            sessionProvider = new SessionManager(sessionFactory);
            CurrentPagedDAO = new EnterprisePagedDAO(sessionProvider);

            this.currentSession = sessionFactory.OpenSession();
        }
        public static ISession GetCurrentSession(ISessionFactory sessionFactory)
        {
            // Option 1 (see also Dispose method)
            // Use GetCurrentSession method
            // see http://stackoverflow.com/questions/1035466/fluentnhibernate-and-not-recognizing-the-session
            //ISession session = null;
            //try
            //{
            //    session = sessionFactory.GetCurrentSession();
            //}
            //catch (HibernateException)
            //{
            //    // do nothing here -- leave session as null
            //}

            //if (session == null)
            //{
            //    session = sessionFactory.OpenSession();
            //    CurrentSessionContext.Bind(session);
            //}

            //return sessionFactory.GetCurrentSession();

            // Option 2
            // Or this is simpler...
            if (_session == null)
            {
                _session = sessionFactory.OpenSession();
            }
            return _session;
        }
		public void SetUp()
		{
			var configuration = new Configuration();
			configuration
				.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "true")
				.SetProperty(NHibernate.Cfg.Environment.Hbm2ddlAuto, "create-drop")
				.SetProperty(NHibernate.Cfg.Environment.UseQueryCache, "true")
				.SetProperty(NHibernate.Cfg.Environment.CacheProvider, typeof (HashtableCacheProvider).AssemblyQualifiedName)
				.SetProperty(NHibernate.Cfg.Environment.ReleaseConnections, "on_close")
				.SetProperty(NHibernate.Cfg.Environment.Dialect, typeof (SQLiteDialect).AssemblyQualifiedName)
				.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, typeof (SQLite20Driver).AssemblyQualifiedName)
				.SetProperty(NHibernate.Cfg.Environment.ConnectionString, "Data Source=:memory:;Version=3;New=True;");

			var assembly = Assembly.GetExecutingAssembly();

			var modelMapper = new ModelMapper();
			modelMapper.AddMappings(assembly.GetTypes());
			var hbms = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
			configuration.AddDeserializedMapping(hbms, assembly.GetName().Name);

			ConfigureSearch(configuration);

			sessionFactory = configuration.BuildSessionFactory();

			Session = sessionFactory.OpenSession();
			SearchSession = Search.CreateFullTextSession(Session);

			new SchemaExport(configuration)
				.Execute(false, true, false, Session.Connection, null);

			AfterSetup();
		}
 public void TestFixtureSetUp()
 {
     configuration = new Configuration();
     configuration.SessionFactory()
                  .Integrate.Using<SQLiteDialect>()
                  .Connected.Using("Data source=testdb")
                  .AutoQuoteKeywords()
                  .LogSqlInConsole()
                  .EnableLogFormattedSql();
     var mapper = new ConventionModelMapper();
     mapper.Class<Foo>(cm => { });
     mapper.Class<Bar>(cm => { });
     CustomizeMapping(mapper);
     var mappingDocument = mapper.CompileMappingForAllExplicitlyAddedEntities();
     new XmlSerializer(typeof(HbmMapping)).Serialize(Console.Out, mappingDocument);
     configuration.AddDeserializedMapping(mappingDocument, "Mappings");
     new SchemaExport(configuration).Create(true, true);
     sessionFactory = configuration.BuildSessionFactory();
     using (var session = sessionFactory.OpenSession())
     using (var tx = session.BeginTransaction())
     {
         var foo = new Foo { Bars = CreateCollection() };
         foo.Bars.Add(new Bar { Data = 1 });
         foo.Bars.Add(new Bar { Data = 2 });
         id = session.Save(foo);
         tx.Commit();
     }
     sessionFactory.Statistics.IsStatisticsEnabled = true;
 }
 public UnitOfWork(ISessionFactory sessionFactory)
 {
     _sessionFactory = sessionFactory;
     CurrentSession = _sessionFactory.OpenSession();
     //CurrentSession.EnableFilter("translationFilter").SetParameter("locale", Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName);
     _transaction = CurrentSession.BeginTransaction();
 }
Example #31
0
        public object GetObjectById(Type type, int id)
        {
            ISession session = _sessionManager.OpenSession();

            return(session.Load(type, id));
        }
Example #32
0
 public UnitOfWork(ISessionFactory sessionFactory)
 {
     _session     = sessionFactory.OpenSession();
     _transaction = _session.BeginTransaction(IsolationLevel.ReadCommitted);
 }
 public ISession GetSession()
 {
     return(sessionFactory.OpenSession());
 }
Example #34
0
 public static void OpenSession()
 {
     HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession();
 }
Example #35
0
 protected override ISession CreateSession()
 {
     return(SessionFactory.OpenSession());
 }
Example #36
0
        public int GetTotalPages(int pageSize)
        {
            using (var session = sessionFactory.OpenSession())
            {
                var pageTotal = session.Query <Product>().Count();

                var shouldAddOne = !(pageTotal % pageSize == 0);
                if (shouldAddOne)
                {
                    pageTotal = pageTotal / pageSize + 1;
                }
                else
                {
                    pageTotal = pageTotal / pageSize;
                }
                return(pageTotal);
            }
        }
Example #37
0
 public ISession OpenSession()
 {
     return(_sessionFactory.OpenSession());
 }
Example #38
0
 protected ISession GetSession()
 {
     return(m_sessionFactory.OpenSession());
 }
Example #39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UnitOfWork"/> class.
 /// </summary>
 public UnitOfWork()
 {
     this.Session     = sessionFactory.OpenSession();
     this.transaction = this.Session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
 }
Example #40
0
        public void CollectionFetchVsLoad()
        {
            IStatistics stats = Sfi.Statistics;

            stats.Clear();

            ISession     s      = OpenSession();
            ITransaction tx     = s.BeginTransaction();
            Continent    europe = FillDb(s);

            tx.Commit();
            s.Clear();

            tx = s.BeginTransaction();
            Assert.AreEqual(0, stats.CollectionLoadCount);
            Assert.AreEqual(0, stats.CollectionFetchCount);
            Continent europe2 = s.Get <Continent>(europe.Id);

            Assert.AreEqual(0, stats.CollectionLoadCount, "Lazy true: no collection should be loaded");
            Assert.AreEqual(0, stats.CollectionFetchCount);

            int cc = europe2.Countries.Count;

            Assert.AreEqual(1, stats.CollectionLoadCount);
            Assert.AreEqual(1, stats.CollectionFetchCount, "Explicit fetch of the collection state");
            tx.Commit();
            s.Close();

            s  = OpenSession();
            tx = s.BeginTransaction();
            stats.Clear();
            europe = FillDb(s);
            tx.Commit();
            s.Clear();
            tx = s.BeginTransaction();
            Assert.AreEqual(0, stats.CollectionLoadCount);
            Assert.AreEqual(0, stats.CollectionFetchCount);

            europe2 = s.CreateQuery("from Continent a join fetch a.Countries where a.id = " + europe.Id).UniqueResult <Continent>();
            Assert.AreEqual(1, stats.CollectionLoadCount);
            Assert.AreEqual(0, stats.CollectionFetchCount, "collection should be loaded in the same query as its parent");
            tx.Commit();
            s.Close();

            Mapping.Collection coll = cfg.GetCollectionMapping("NHibernate.Test.Stats.Continent.Countries");
            coll.FetchMode = FetchMode.Join;
            coll.IsLazy    = false;
            ISessionFactory sf = cfg.BuildSessionFactory();

            stats = sf.Statistics;
            stats.Clear();
            stats.IsStatisticsEnabled = true;
            s      = sf.OpenSession();
            tx     = s.BeginTransaction();
            europe = FillDb(s);
            tx.Commit();
            s.Clear();
            tx = s.BeginTransaction();
            Assert.AreEqual(0, stats.CollectionLoadCount);
            Assert.AreEqual(0, stats.CollectionFetchCount);

            europe2 = s.Get <Continent>(europe.Id);
            Assert.AreEqual(1, stats.CollectionLoadCount);
            Assert.AreEqual(0, stats.CollectionFetchCount,
                            "Should do direct load, not indirect second load when lazy false and JOIN");
            tx.Commit();
            s.Close();
            sf.Close();

            coll           = cfg.GetCollectionMapping("NHibernate.Test.Stats.Continent.Countries");
            coll.FetchMode = FetchMode.Select;
            coll.IsLazy    = false;
            sf             = cfg.BuildSessionFactory();
            stats          = sf.Statistics;
            stats.Clear();
            stats.IsStatisticsEnabled = true;
            s      = sf.OpenSession();
            tx     = s.BeginTransaction();
            europe = FillDb(s);
            tx.Commit();
            s.Clear();
            tx = s.BeginTransaction();
            Assert.AreEqual(0, stats.CollectionLoadCount);
            Assert.AreEqual(0, stats.CollectionFetchCount);
            europe2 = s.Get <Continent>(europe.Id);
            Assert.AreEqual(1, stats.CollectionLoadCount);
            Assert.AreEqual(1, stats.CollectionFetchCount, "Should do explicit collection load, not part of the first one");
            foreach (Country country in europe2.Countries)
            {
                s.Delete(country);
            }
            CleanDb(s);
            tx.Commit();
            s.Close();
        }
Example #41
0
 public ISession OpenSession()
 {
     return(session ?? (session = sessionFactory.OpenSession()));
 }
 public static ISession OpenSession()
 {
     return(SessionFactory?.OpenSession());
 }
Example #43
0
 public UnitOfWork(ISessionFactory sessionFactory)
 {
     _sessionFactory = sessionFactory;
     Session         = _sessionFactory.OpenSession();
     _transaction    = Session.BeginTransaction();
 }
        public async Task CreateUser()
        {
            // Create a session and user store for this test.
            var session   = SessionFactory.OpenSession();
            var userStore = new TestUserStore(session);
            // Create and save a user.
            var user = new TestUser {
                UserName = "******"
            };

            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);

                transaction.Commit();
            }
            // Check the user has an id.
            Assert.IsNotNull(user.Id);

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session   = SessionFactory.OpenSession();
            userStore = new TestUserStore(session);
            // Load the user.
            TestUser loadUser;

            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(user.Id);

                transaction.Commit();
            }
            // Check we have the same user.
            Assert.AreEqual(user.Id, loadUser.Id);
            Assert.AreEqual(user.UserName, loadUser.UserName);
        }
Example #45
0
 private static void PopulateDatabase(ISessionFactory sessionFactory, NodaTimeOffsetTime time)
 {
     using var session = sessionFactory.OpenSession();
     session.Save(time);
     session.Flush();
 }
Example #46
0
 public IList <License> GetAll()
 {
     using (var session = sessionFactory.OpenSession())
     {
         var results = session.CreateCriteria <License>().List <License>();
         return(results);
     }
 }
Example #47
0
 public void BeginTransaction()
 {
     Session     = sessionFactory.OpenSession();
     transaction = Session.BeginTransaction();
 }
 public IPersistence GetInstance()
 {
     return(new NHibernatePersistence(_sessionFactory.OpenSession()));
 }
Example #49
0
 public static ISession AbrirConexao()
 {
     // Com a atribuição da sessão a uma propriedade estática, possuo uma única
     // sessão com a base de dados ao longo do ciclo do meu projeto...
     return(session.OpenSession());
 }
Example #50
0
        public static ISession OpenSession()
        {
            var session = sessionFactory.OpenSession();

            return(session);
        }
Example #51
0
 private static void CleanDatabase(ISessionFactory sessionFactory)
 {
     using var session = sessionFactory.OpenSession();
     session.Query <NodaTimeOffsetTime>().Delete();
     session.Flush();
 }
Example #52
0
 public ISession OpenSession(IDbConnection conn)
 {
     return(_inner.OpenSession(_liveConnection));
 }
Example #53
0
 public static ISession GetCurrentSession()
 {
     return(_sessionFactory.OpenSession());
 }
Example #54
0
 public OrderUnityOfWork()
 {
     _session = SessionFactory.OpenSession();
 }
Example #55
0
        static void FillDB()
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                CategorieRepository categorieRepository = new CategorieRepository();
                Categorie           manga = new Categorie("Manga");
                Categorie           bd    = new Categorie("BD");
                Categorie           comic = new Categorie("Comic");

                GenreRepository genreRepository          = new GenreRepository();
                Genre           drame                    = new Genre("Drame");
                Genre           fantastique              = new Genre("Fantastique");
                Genre           humour                   = new Genre("Humour");
                Genre           suspense                 = new Genre("Suspense");
                Genre           polarThriller            = new Genre("Polar/Thriller");
                Genre           francoBelge              = new Genre("Franco-Belge");
                Genre           aventure                 = new Genre("Aventure");
                Genre           biographie               = new Genre("Biographie");
                Genre           superHeros               = new Genre("Super-Héros");
                Genre           jeunesse                 = new Genre("Jeunesse");
                Genre           western                  = new Genre("Western");
                Genre           documentaireEncyclopedie = new Genre("Documentaire/Encyclopédie");
                Genre           belge                    = new Genre("Belge");

                SerieRepository serieRepository = new SerieRepository();
                Serie           deathNote       = new Serie("Death Note");
                Serie           gaston          = new Serie("Gaston");
                Serie           tintin          = new Serie("Tintin");
                Serie           persepolis      = new Serie("Persepolis");
                Serie           asterix         = new Serie("Astérix");
                Serie           rubriqueabrac   = new Serie("Rubrique-à-Brac");
                Serie           watchmen        = new Serie("Watchmen");
                Serie           schtroumpfs     = new Serie("Les Schtroumpfs");
                Serie           lechat          = new Serie("Le Chat");
                Serie           luckyLuke       = new Serie("Lucky Luke");
                Serie           civilWar        = new Serie("Civil War");
                Serie           maus            = new Serie("Maus");
                Serie           calvinHobbes    = new Serie("Calvin et Hobbes");

                AuteurRepository auteurRepository = new AuteurRepository();
                Auteur           ohba             = new Auteur("Tsugumi", "Ohba");
                Auteur           obata            = new Auteur("Takeshi", "Obata");
                Auteur           franquin         = new Auteur("André", "Franquin");
                Auteur           jidehem          = new Auteur("Jidéhem", "");
                Auteur           herge            = new Auteur("Hergé", "");
                Auteur           strapi           = new Auteur("Marjane", "Strapi");
                Auteur           goscinny         = new Auteur("René", "Goscinny");
                Auteur           gotlib           = new Auteur("Gotlib", "");
                Auteur           moore            = new Auteur("Alan", "Moore");
                Auteur           peyo             = new Auteur("Peyo", "");
                Auteur           delporte         = new Auteur("Yvan", "Delporte");
                Auteur           geluck           = new Auteur("Philippe", "Geluck");
                Auteur           morris           = new Auteur("Morris", "");
                Auteur           millar           = new Auteur("Mark", "Millar");
                Auteur           spiegelman       = new Auteur("Art", "Spiegelman");
                Auteur           uderzo           = new Auteur("Albert", "Uderzo");
                Auteur           watterson        = new Auteur("Bill", "Watterson");
                Auteur           mcniven          = new Auteur("Steve", "McNiven");

                EditeurRepository editeurRepository = new EditeurRepository();
                Editeur           kana           = new Editeur("Kana");
                Editeur           dupuis         = new Editeur("Dupuis");
                Editeur           casterman      = new Editeur("Casterman");
                Editeur           lassociation   = new Editeur("L'association");
                Editeur           hachette       = new Editeur("Hacette Livre");
                Editeur           dargaud        = new Editeur("Dargaud");
                Editeur           dc             = new Editeur("DC Comics");
                Editeur           marvel         = new Editeur("Marvel France");
                Editeur           flammarion     = new Editeur("Flammarion");
                Editeur           lombard        = new Editeur("Lombard");
                Editeur           horscollection = new Editeur("Hors Collection");

                AlbumRepository albumRepository = new AlbumRepository();
                Album           alb1            = new Album("death-note-t1.jpg", "Death Note - Tome 1", manga, kana, deathNote);
                alb1.Auteurs.Add(ohba);
                alb1.Auteurs.Add(obata);
                alb1.Genres.Add(drame);
                alb1.Genres.Add(fantastique);
                alb1.Genres.Add(polarThriller);
                alb1.Genres.Add(suspense);

                Album alb2 = new Album("les-archives-de-lagaffe.jpg", "Les archives de Lagaffe", bd, dupuis, gaston);
                alb2.Auteurs.Add(franquin);
                alb2.Auteurs.Add(jidehem);
                alb2.Genres.Add(francoBelge);
                alb2.Genres.Add(humour);

                Album alb3 = new Album("tintin-au-tibet.jpg", "Tintin au Tibet", bd, casterman, tintin);
                alb3.Auteurs.Add(herge);
                alb3.Genres.Add(francoBelge);
                alb3.Genres.Add(humour);

                Album alb4 = new Album("persepolis.jpg", "Persepolis - Tome 1", bd, lassociation, persepolis);
                alb4.Auteurs.Add(strapi);
                alb4.Genres.Add(biographie);

                Album alb5 = new Album("asterix-le-gaulois.jpg", "Astérix le Gaulois - Astérix Tome 1 ", bd, hachette, asterix);
                alb5.Auteurs.Add(goscinny);
                alb5.Genres.Add(humour);

                Album alb6 = new Album("rubrique-a-brac.jpg", "Rubrique-à-brac - Tome 1 ", bd, dargaud, rubriqueabrac);
                alb6.Auteurs.Add(gotlib);
                alb6.Genres.Add(humour);

                Album alb7 = new Album("watchmen-1.jpg", "Watchmen - Vol 1", comic, dc, watchmen);
                alb7.Auteurs.Add(moore);
                alb7.Genres.Add(superHeros);

                Album alb8 = new Album("schtroumpfs-noirs.jpg", "Les Schtroumpfs Noirs ", bd, dupuis, schtroumpfs);
                alb8.Auteurs.Add(peyo);
                alb8.Genres.Add(aventure);
                alb8.Genres.Add(jeunesse);

                Album alb9 = new Album("le-chat.jpg", "Le Chat - Tome 1", bd, casterman, lechat);
                alb9.Auteurs.Add(geluck);
                alb9.Genres.Add(humour);

                Album alb10 = new Album("la-guerison-des-daltons.jpg", "La guérison des Daltons", bd, dargaud, luckyLuke);
                alb10.Auteurs.Add(goscinny);
                alb10.Auteurs.Add(morris);
                alb10.Genres.Add(humour);
                alb10.Genres.Add(belge);
                alb10.Genres.Add(western);

                Album alb11 = new Album("maus-t1.jpg", "Maus - Tome 1 : Un survivant raconte ", bd, flammarion, maus);
                alb11.Auteurs.Add(spiegelman);
                alb11.Genres.Add(documentaireEncyclopedie);

                Album alb12 = new Album("asterix-la-serpe-dor.jpg", "Astérix - 2 - La serpe d'or", bd, dargaud, asterix);
                alb12.Auteurs.Add(goscinny);
                alb12.Auteurs.Add(uderzo);
                alb12.Genres.Add(humour);

                Album alb13 = new Album("civil-war.jpg", "Civil War - Tome 01 ", comic, marvel, civilWar);
                alb13.Auteurs.Add(millar);
                alb13.Auteurs.Add(mcniven);
                alb13.Genres.Add(superHeros);

                Album alb14 = new Album("calvin-hobbes.jpg", "Calvin et Hobbes - Tome 1 - Adieu monde cruel !", bd, horscollection, calvinHobbes);
                alb14.Auteurs.Add(watterson);
                alb14.Genres.Add(humour);

                Album alb15 = new Album("tintin-au-pays-soviets.jpg", "Tintin au pays des Soviets", bd, casterman, tintin);
                alb15.Auteurs.Add(herge);
                alb15.Genres.Add(aventure);
                alb15.Genres.Add(francoBelge);

                UtilisateurRepository utilisateurRepository = new UtilisateurRepository();
                Utilisateur           bpesquet  = new Utilisateur("bpesquet", "jaimelegenielog");
                Utilisateur           sbertrand = new Utilisateur("sbertrand", "moiaussijaimelegenielog");
                Utilisateur           lulu31    = new Utilisateur("lulu31", "coucou");

                categorieRepository.Save(manga);
                categorieRepository.Save(bd);
                categorieRepository.Save(comic);

                genreRepository.Save(drame);
                genreRepository.Save(fantastique);
                genreRepository.Save(polarThriller);
                genreRepository.Save(suspense);
                genreRepository.Save(francoBelge);
                genreRepository.Save(humour);
                genreRepository.Save(superHeros);
                genreRepository.Save(biographie);
                genreRepository.Save(aventure);
                genreRepository.Save(jeunesse);
                genreRepository.Save(belge);
                genreRepository.Save(western);
                genreRepository.Save(documentaireEncyclopedie);

                editeurRepository.Save(kana);
                editeurRepository.Save(dupuis);
                editeurRepository.Save(casterman);
                editeurRepository.Save(lassociation);
                editeurRepository.Save(hachette);
                editeurRepository.Save(dargaud);
                editeurRepository.Save(dc);
                editeurRepository.Save(marvel);
                editeurRepository.Save(flammarion);
                editeurRepository.Save(lombard);
                editeurRepository.Save(horscollection);

                auteurRepository.Save(ohba);
                auteurRepository.Save(franquin);
                auteurRepository.Save(herge);
                auteurRepository.Save(strapi);
                auteurRepository.Save(goscinny);
                auteurRepository.Save(moore);
                auteurRepository.Save(peyo);
                auteurRepository.Save(delporte);
                auteurRepository.Save(geluck);
                auteurRepository.Save(morris);
                auteurRepository.Save(millar);
                auteurRepository.Save(spiegelman);
                auteurRepository.Save(uderzo);
                auteurRepository.Save(watterson);

                serieRepository.Save(deathNote);
                serieRepository.Save(gaston);
                serieRepository.Save(tintin);
                serieRepository.Save(persepolis);
                serieRepository.Save(asterix);
                serieRepository.Save(rubriqueabrac);
                serieRepository.Save(watchmen);
                serieRepository.Save(schtroumpfs);
                serieRepository.Save(lechat);
                serieRepository.Save(luckyLuke);
                serieRepository.Save(civilWar);
                serieRepository.Save(maus);
                serieRepository.Save(calvinHobbes);

                albumRepository.Save(alb1);
                albumRepository.Save(alb2);
                albumRepository.Save(alb3);
                albumRepository.Save(alb4);
                albumRepository.Save(alb5);
                albumRepository.Save(alb6);
                albumRepository.Save(alb7);
                albumRepository.Save(alb8);
                albumRepository.Save(alb9);
                albumRepository.Save(alb10);
                albumRepository.Save(alb11);
                albumRepository.Save(alb12);
                albumRepository.Save(alb13);
                albumRepository.Save(alb14);
                albumRepository.Save(alb15);

                utilisateurRepository.Save(bpesquet);
                utilisateurRepository.Save(sbertrand);
                utilisateurRepository.Save(lulu31);

                session.Clear();
            }
        }
 internal static ISession OpenSession()
 {
     return(_sessionFactory.OpenSession());
 }
Example #57
0
 public static ISession OpenSessionWithConnection(this ISessionFactory sessionFactory, DbConnection connection)
 {
     return(sessionFactory.OpenSession().OpenSessionWithConnection(connection));
 }
Example #58
0
 public Usuario getUsuario(int id)
 {
     return(fabrica.OpenSession().Get <Usuario>(id));
 }
Example #59
0
        /// <summary>
        /// Explicitly open a session. If you have an open session, close it first.
        /// </summary>
        /// <returns>The <see cref="NHibernate.ISession"/></returns>
        public ISession OpenSession()
        {
            ISession session = SessionFactory.OpenSession();

            return(session);
        }
Example #60
0
        public void Start()
        {
            AssertInValidState();

            CurrentSession = _factory.OpenSession(_connectionProvider.GetConnection());
        }