当前位置: 首页>>代码示例>>C#>>正文


C# ISessionFactory.OpenSession方法代码示例

本文整理汇总了C#中ISessionFactory.OpenSession方法的典型用法代码示例。如果您正苦于以下问题:C# ISessionFactory.OpenSession方法的具体用法?C# ISessionFactory.OpenSession怎么用?C# ISessionFactory.OpenSession使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ISessionFactory的用法示例。


在下文中一共展示了ISessionFactory.OpenSession方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: InitializeTiles

        /// <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();
                }
            }
        }
开发者ID:Rawne,项目名称:laststand,代码行数:30,代码来源:MapTileFactory.cs

示例2: FullInitializedRetrievedEntity

			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();
				}
			}
开发者ID:owerkop,项目名称:nhibernate-core,代码行数:25,代码来源:CheckViability.cs

示例3: getExistingOrNewSession

        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;
        }
开发者ID:phiree,项目名称:testttt,代码行数:28,代码来源:HybridSessionBuilder.cs

示例4: CanReadAndSavePerson

        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"));
                }
            }
        }
开发者ID:Marceli,项目名称:JQueryGridTest,代码行数:25,代码来源:NHibernateExplanationTestSQLServer.cs

示例5: Run

        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");
                }
            }
        }
开发者ID:diabluchanskyi,项目名称:pablo,代码行数:53,代码来源:1_Save_Load_and_Delete_Example.cs

示例6: GetExistingOrNewSession

        private ISession GetExistingOrNewSession(ISessionFactory factory)
        {
            if (_currentSession == null)
            {
                _currentSession = factory.OpenSession();
            }
            else if (!_currentSession.IsOpen)
            {
                _currentSession = factory.OpenSession();
            }

            return _currentSession;
        }
开发者ID:santos-rafaelcarlos,项目名称:Prova_Colegio_Asp.net,代码行数:13,代码来源:HybridSessionBuilder.cs

示例7: Run

        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();
            }
        }
开发者ID:diabluchanskyi,项目名称:pablo,代码行数:51,代码来源:3_CRUD_with_Collections.cs

示例8: SqlLiteBuilder

        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);
        }
开发者ID:chrisblock,项目名称:Criteria,代码行数:28,代码来源:SqlLiteBuilder.cs

示例9: Form1

        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();
        }
开发者ID:TheHunter,项目名称:WFPersistentLayerTester,代码行数:29,代码来源:Form1.cs

示例10: MapScenario

			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();
					}
				}
			}
开发者ID:NikGovorov,项目名称:nhibernate-core,代码行数:31,代码来源:Fixture.cs

示例11: SavePostsWithHilo

        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");
            }
        }
开发者ID:stevenlauwers22,项目名称:NHibernate.DotNetAcademy,代码行数:25,代码来源:Program.cs

示例12: Seed

        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;
        }
开发者ID:spidermoore,项目名称:peerconnect,代码行数:29,代码来源:NinjectWebClientModule.cs

示例13: DatabaseFixture

        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();
        }
开发者ID:tobinharris,项目名称:rhino-security,代码行数:31,代码来源:DatabaseFixture.cs

示例14: GenerateData

 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();
         }
     }
 }
开发者ID:abrobston,项目名称:NHibernate.Spatial,代码行数:25,代码来源:DataGenerator.cs

示例15: UseNHibernate

        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>()));
        }
开发者ID:mouhong,项目名称:Taro,代码行数:7,代码来源:NHibernateConfiguration.cs


注:本文中的ISessionFactory.OpenSession方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。