示例#1
0
        public async Task TestUpdateEmployeeAsync()
        {
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    Employee[] employees = await(CreateAndInsertEmployeesAsync(s, 3));

                    Employee emp0 = (Employee)await(s.GetAsync(typeof(Employee), employees[0].Id));
                    Assert.IsNotNull(emp0);
                    emp0.Address       = "Address";
                    emp0.BusinessPhone = "BusinessPhone";
                    emp0.Country       = "Country";
                    emp0.HomePhone     = "HomePhone";
                    emp0.Manager       = employees[2];
                    emp0.Name          = "Name";
                    emp0.Salary        = 20000;
                    emp0.Title         = "Title";
                    emp0.Zip           = "Zip";
                    await(NHibernateUtil.InitializeAsync(emp0.Meetings));
                    await(NHibernateUtil.InitializeAsync(emp0.OthersPhones));
                    emp0.Meetings.Add(new Meeting {
                        Employee = emp0, Description = "vacation def"
                    });
                    // Not updating emp0.Sex because it is marked update=false in the mapping file.

                    await(s.FlushAsync());
                    s.Clear();

                    Employee emp0updated = (Employee)await(s.GetAsync(typeof(Employee), employees[0].Id));
                    Assert.IsTrue(EmployeesAreEqual(emp0, emp0updated));

                    await(tx.CommitAsync());
                }
        }
示例#2
0
        public async Task DeleteItemFromCollectionThatIsInTheSecondLevelCacheAsync()
        {
            using (ISession session = OpenSession())
            {
                Item item = (Item)await(session.LoadAsync(typeof(Item), 1));
                Assert.IsTrue(item.Children.Count == 4);                 // just force it into the second level cache here
            }
            int childId = -1;

            using (ISession session = OpenSession())
            {
                Item item  = (Item)await(session.LoadAsync(typeof(Item), 1));
                Item child = (Item)item.Children[0];
                childId = child.Id;
                await(session.DeleteAsync(child));
                item.Children.Remove(child);
                await(session.FlushAsync());
            }

            using (ISession session = OpenSession())
            {
                Item item = (Item)await(session.LoadAsync(typeof(Item), 1));
                Assert.AreEqual(3, item.Children.Count);
                foreach (Item child in item.Children)
                {
                    await(NHibernateUtil.InitializeAsync(child));
                    Assert.IsFalse(child.Id == childId);
                }
            }
        }
示例#3
0
        /// <inheritdoc />
        public async IAsyncEnumerable <(EntityInfo EntityInfo, Object Entity)> LoadAsync(IReadOnlyList <EntityInfo> entityInfos, [EnumeratorCancellation] CancellationToken token = default)
        {
            // Use load to benefit from the batch-size
            // We don't face proxy casting issues since the exact class is extracted from the index
            // TODO: Why do this?
            //foreach (EntityInfo entityInfo in entityInfos)
            //{
            //    await session.LoadAsync(entityInfo.Clazz, entityInfo.Id);
            //}

            foreach (EntityInfo entityInfo in entityInfos)
            {
                object entity;

                try
                {
                    entity = await session.LoadAsync(entityInfo.Clazz, entityInfo.Id, token);

                    await NHibernateUtil.InitializeAsync(entity, token);
                }
                catch (Exception e)
                {
                    if (!IsEntityNotFound(e, entityInfo))
                    {
                        throw;
                    }

                    entity = null;
                }

                yield return(entityInfo, entity);
            }
        }
示例#4
0
        public async Task GetGoodErrorForDirtyReassociatedCollectionAsync()
        {
            Person person;

            using (var s = OpenSession())
                using (s.BeginTransaction())
                {
                    person = await(s.GetAsync <Person>(1));
                    await(NHibernateUtil.InitializeAsync(person.Children));
                    await(s.Transaction.CommitAsync());
                }

            person.Children.Clear();

            using (var s = OpenSession())
                using (s.BeginTransaction())
                {
                    Assert.That(
                        () =>
                    {
                        return(s.LockAsync(person, LockMode.None));
                    },
                        Throws.TypeOf <HibernateException>()
                        .And.Message.EqualTo(
                            "reassociated object has dirty collection: NHibernate.Test.NHSpecificTest.NH2065.Person.Children"));
                }
        }
示例#5
0
        public async Task LazyLoad_Initialize_AndEvictAsync()
        {
            Category category = new Category("parent");

            category.AddSubcategory(new Category("child"));
            await(SaveCategoryAsync(category));

            using (ISession session = OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    Category loaded = await(session.LoadAsync <Category>(category.Id));
                    await(NHibernateUtil.InitializeAsync(loaded.Subcategories[0]));
                    await(session.EvictAsync(loaded));
                    await(transaction.CommitAsync());
                    Assert.AreEqual("child", loaded.Subcategories[0].Name, "cannot access child");
                }
            using (ISession session = OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    // first delete children
                    await(session.CreateQuery("delete from Category where Parent != null").ExecuteUpdateAsync());
                    // then the rest
                    await(session.CreateQuery("delete from Category").ExecuteUpdateAsync());
                    await(transaction.CommitAsync());
                }
        }
示例#6
0
        public async Task IntializeForwaredToPersistentCollectionAsync()
        {
            var collection = Substitute.For <IPersistentCollection>();

            await(NHibernateUtil.InitializeAsync(collection));

            await(collection.Received().ForceInitializationAsync(CancellationToken.None));
        }
        private async Task AssertMultipleCacheCollectionCallsAsync(List <int> ids, int idIndex, int[][] fetchedIdIndexes, int[] putIdIndexes, Func <int, bool> cacheBeforeLoadFn = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var persister = Sfi.GetCollectionPersister($"{typeof(ReadOnly).FullName}.Items");
            var cache     = (BatchableCache)persister.Cache.Cache;

            await(cache.ClearAsync(cancellationToken));

            if (cacheBeforeLoadFn != null)
            {
                using (var s = Sfi.OpenSession())
                    using (var tx = s.BeginTransaction())
                    {
                        foreach (var id in ids.Where((o, i) => cacheBeforeLoadFn(i)))
                        {
                            var item = await(s.GetAsync <ReadOnly>(id, cancellationToken));
                            await(NHibernateUtil.InitializeAsync(item.Items, cancellationToken));
                        }
                        await(tx.CommitAsync(cancellationToken));
                    }
            }

            using (var s = Sfi.OpenSession())
                using (var tx = s.BeginTransaction())
                {
                    cache.ClearStatistics();

                    foreach (var id in ids)
                    {
                        await(s.GetAsync <ReadOnly>(id, cancellationToken));
                    }
                    var item = await(s.GetAsync <ReadOnly>(ids[idIndex], cancellationToken));
                    Assert.That(item, Is.Not.Null);
                    await(NHibernateUtil.InitializeAsync(item.Items, cancellationToken));
                    Assert.That(cache.GetCalls, Has.Count.EqualTo(0));
                    Assert.That(cache.PutCalls, Has.Count.EqualTo(0));
                    Assert.That(cache.GetMultipleCalls, Has.Count.EqualTo(fetchedIdIndexes.GetLength(0)));
                    if (putIdIndexes == null)
                    {
                        Assert.That(cache.PutMultipleCalls, Has.Count.EqualTo(0));
                    }
                    else
                    {
                        Assert.That(cache.PutMultipleCalls, Has.Count.EqualTo(1));
                        Assert.That(
                            cache.PutMultipleCalls[0].OfType <CacheKey>().Select(o => (int)o.Key),
                            Is.EquivalentTo(putIdIndexes.Select(o => ids[o])));
                    }

                    for (int i = 0; i < fetchedIdIndexes.GetLength(0); i++)
                    {
                        Assert.That(
                            cache.GetMultipleCalls[i].OfType <CacheKey>().Select(o => (int)o.Key),
                            Is.EquivalentTo(fetchedIdIndexes[i].Select(o => ids[o])));
                    }

                    await(tx.CommitAsync(cancellationToken));
                }
        }
示例#8
0
 private async Task <Blob> LoadDetachedBlobAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     using (ISession session = OpenSession())
         using (session.BeginTransaction())
         {
             var blob = await(session.GetAsync <Blob>(_blobId, cancellationToken));
             await(NHibernateUtil.InitializeAsync(blob.Bytes, cancellationToken));
             return(blob);
         }
 }
示例#9
0
        public void InitializeManyToOneNotNullAsync()
        {
            var parent = AuditReader().Find <Parent>(parentId, 2);

            NHibernateUtil.IsInitialized(parent.RelatedEntity).Should().Be.False();
            NHibernateUtil.InitializeAsync(parent.RelatedEntity);
            NHibernateUtil.IsInitialized(parent.RelatedEntity).Should().Be.True();
            parent.RelatedEntity.Id.Should().Be.EqualTo(relatedId);
            parent.RelatedEntity.Str.Should().Be.EqualTo("R_1_1");
        }
示例#10
0
 private async Task <Entity> CreateInitializedProxyAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var s = OpenSession())
         using (s.BeginTransaction())
         {
             var proxyEntity = await(s.LoadAsync <Entity>(id, cancellationToken));
             await(NHibernateUtil.InitializeAsync(proxyEntity, cancellationToken));
             return(proxyEntity);
         }
 }
示例#11
0
 public async Task SOEOnLoadAsync()
 {
     using (var session = OpenSession())
         using (session.BeginTransaction())
         {
             var superParent = await(session.LoadAsync <SuperParent>(_superParentId));
             Assert.That(() => NHibernateUtil.InitializeAsync(superParent), Throws.Nothing);
             Assert.That(() => NHibernateUtil.InitializeAsync(superParent.Parent), Throws.Nothing);
         }
 }
示例#12
0
 public async Task ShouldThrowExceptionIfIdChangedOnLoadEntityAsync()
 {
     using (var s = OpenSession())
         using (var tx = s.BeginTransaction())
         {
             var entity = await(s.LoadAsync <Entity>(id));
             await(NHibernateUtil.InitializeAsync(entity));
             entity.Id++;
             Assert.ThrowsAsync <HibernateException>(() => tx.CommitAsync());
         }
 }
示例#13
0
        public async Task CachedCollectionRefreshAsync()
        {
            if (!TestDialect.SupportsEmptyInsertsOrHasNonIdentityNativeGenerator)
            {
                Assert.Ignore("Support of empty inserts is required");
            }

            ISession         s    = OpenSession();
            Category         c    = new Category();
            IList <Category> list = new List <Category>();

            c.Subcategories = list;
            list.Add(new Category());
            c.Name = "root";
            object id = await(s.SaveAsync(c));

            await(s.FlushAsync());
            s.Close();

            s = OpenSession();
            c = (Category)await(s.LoadAsync(typeof(Category), id));
            await(NHibernateUtil.InitializeAsync(c.Subcategories));

            ISession ss = OpenSession();
            Category c2 = (Category)await(ss.LoadAsync(typeof(Category), id));

            await(ss.DeleteAsync(c2.Subcategories[0]));
            c2.Subcategories.Clear();
            await(ss.FlushAsync());
            ss.Close();

            await(s.RefreshAsync(c));
            Assert.AreEqual(0, c.Subcategories.Count);

            ss = OpenSession();
            c2 = (Category)await(ss.LoadAsync(typeof(Category), id));
            c2.Subcategories.Add(new Category());
            c2.Subcategories.Add(new Category());
            await(ss.FlushAsync());
            ss.Close();

            await(s.RefreshAsync(c));
            Assert.AreEqual(2, c.Subcategories.Count);

            await(s.FlushAsync());
            s.Close();

            s = OpenSession();
            c = (Category)await(s.LoadAsync(typeof(Category), id));
            Assert.AreEqual(2, c.Subcategories.Count);
            await(s.DeleteAsync(c));
            await(s.FlushAsync());
            s.Close();
        }
示例#14
0
文件: Fixture.cs 项目: jrauber/GH1429
 private async Task AddChildAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     using (ISession session = OpenSession())
         using (ITransaction tx = session.BeginTransaction())
         {
             var   parent = await(session.GetAsync <Parent>(parentId, cancellationToken));
             Child child  = new Child();
             parent.AddChild(child);
             await(NHibernateUtil.InitializeAsync(parent.Children, cancellationToken));
             await(tx.CommitAsync(cancellationToken));
         }
 }
示例#15
0
        public async Task TestHqlAsync()
        {
            // test the Save
            ISession     s = OpenSession();
            ITransaction t = s.BeginTransaction();

            Employee wally = new Employee();

            wally.Name  = "wally";
            wally.Title = "Unmanaged Employee";

            Employee dilbert = new Employee();

            dilbert.Name  = "dilbert";
            dilbert.Title = "office clown";

            Employee pointyhair = new Employee();

            pointyhair.Name  = "pointyhair";
            pointyhair.Title = "clown watcher";

            dilbert.Manager = pointyhair;

            await(s.SaveAsync(wally));
            await(s.SaveAsync(dilbert));
            await(s.SaveAsync(pointyhair));
            await(t.CommitAsync());
            s.Close();

            // get a proxied - initialized version of manager
            s          = OpenSession();
            pointyhair = (Employee)await(s.LoadAsync(typeof(Employee), pointyhair.Id));
            await(NHibernateUtil.InitializeAsync(pointyhair));
            s.Close();

            s = OpenSession();
            t = s.BeginTransaction();
            IQuery q = s.CreateQuery("from Employee as e where e.Manager = :theMgr");

            q.SetParameter("theMgr", pointyhair);
            IList results = await(q.ListAsync());

            Assert.AreEqual(1, results.Count, "should only return 1 employee.");
            dilbert = (Employee)results[0];
            Assert.AreEqual("dilbert", dilbert.Name, "should have been dilbert returned.");

            await(s.DeleteAsync(wally));
            await(s.DeleteAsync(pointyhair));
            await(s.DeleteAsync(dilbert));
            await(s.FlushAsync());
            await(t.CommitAsync());
            s.Close();
        }
示例#16
0
        public async Task CanLazyLoadAsync()
        {
            using (var session = OpenSession())
                using (session.BeginTransaction())
                {
                    var result = await((from e in session.Query <Consumer>()
                                        select e).FirstAsync());

                    Assert.That(result.Child, Is.Not.Null);
                    Assert.DoesNotThrowAsync(() => NHibernateUtil.InitializeAsync(result.Child));
                }
        }
示例#17
0
        public async Task SecondLevelCachedCollectionsFilteringAsync()
        {
            TestData testData = new TestData(this);

            await(testData.PrepareAsync());

            ISession session = OpenSession();

            // Force a collection into the second level cache, with its non-filtered elements
            Salesperson sp = (Salesperson)await(session.LoadAsync(typeof(Salesperson), testData.steveId));

            await(NHibernateUtil.InitializeAsync(sp.Orders));
            ICollectionPersister persister = ((ISessionFactoryImplementor)Sfi)
                                             .GetCollectionPersister(typeof(Salesperson).FullName + ".Orders");

            Assert.IsTrue(persister.HasCache, "No cache for collection");
            CacheKey cacheKey =
                new CacheKey(testData.steveId, persister.KeyType, persister.Role, (ISessionFactoryImplementor)Sfi);
            CollectionCacheEntry cachedData = (CollectionCacheEntry)await(persister.Cache.Cache.GetAsync(cacheKey, CancellationToken.None));

            Assert.IsNotNull(cachedData, "collection was not in cache");

            session.Close();

            session = OpenSession();
            session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth);
            sp = (Salesperson)await(session.CreateQuery("from Salesperson as s where s.id = :id")
                                    .SetInt64("id", testData.steveId)
                                    .UniqueResultAsync());
            Assert.AreEqual(1, sp.Orders.Count, "Filtered-collection not bypassing 2L-cache");

            CollectionCacheEntry cachedData2 = (CollectionCacheEntry)await(persister.Cache.Cache.GetAsync(cacheKey, CancellationToken.None));

            Assert.IsNotNull(cachedData2, "collection no longer in cache!");
            Assert.AreSame(cachedData, cachedData2, "Different cache values!");

            session.Close();

            session = OpenSession();
            session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth);
            sp = (Salesperson)await(session.LoadAsync(typeof(Salesperson), testData.steveId));
            Assert.AreEqual(1, sp.Orders.Count, "Filtered-collection not bypassing 2L-cache");

            session.Close();

            // Finally, make sure that the original cached version did not get over-written
            session = OpenSession();
            sp      = (Salesperson)await(session.LoadAsync(typeof(Salesperson), testData.steveId));
            Assert.AreEqual(2, sp.Orders.Count, "Actual cached version got over-written");

            session.Close();
            await(testData.ReleaseAsync());
        }
 public async Task SetInitializedProxyShouldNotResetPropertyInitializationAsync()
 {
     using (var s = OpenSession())
     {
         var order   = await(s.GetAsync <Order>(1));
         var payment = await(s.LoadAsync <Payment>(2));
         Assert.That(order.Payment is WireTransfer, Is.True);                 // Load property
         Assert.That(NHibernateUtil.IsPropertyInitialized(order, "Payment"), Is.True);
         await(NHibernateUtil.InitializeAsync(payment));
         order.Payment = payment;
         Assert.That(NHibernateUtil.IsPropertyInitialized(order, "Payment"), Is.True);
     }
 }
        public async Task MultiplePutReadWriteItemTestAsync()
        {
            var persister = Sfi.GetCollectionPersister($"{typeof(ReadWrite).FullName}.Items");

            Assert.That(persister.Cache.Cache, Is.Not.Null);
            Assert.That(persister.Cache.Cache, Is.TypeOf <BatchableCache>());
            var cache = (BatchableCache)persister.Cache.Cache;
            var ids   = new List <int>();

            await(cache.ClearAsync(CancellationToken.None));
            cache.ClearStatistics();

            using (var s = Sfi.OpenSession())
                using (var tx = s.BeginTransaction())
                {
                    var items = await(s.Query <ReadWrite>().ToListAsync());
                    ids.AddRange(items.OrderBy(o => o.Id).Select(o => o.Id));

                    // Initialize the first item collection
                    await(NHibernateUtil.InitializeAsync(items.First(o => o.Id == ids[0]).Items));
                    await(tx.CommitAsync());
                }
            Assert.That(cache.PutCalls, Has.Count.EqualTo(0));
            // Called in: DefaultInitializeCollectionEventListener, BatchingCollectionInitializer and ReadWriteCache
            Assert.That(cache.GetMultipleCalls, Has.Count.EqualTo(3));

            AssertEquivalent(
                ids,
                new[]
            {
                new[] { 0, 1, 2, 3, 4 }
            },
                cache.PutMultipleCalls
                );
            AssertEquivalent(
                ids,
                new[]
            {
                new[] { 0, 1, 2, 3, 4 }
            },
                cache.LockMultipleCalls
                );
            AssertEquivalent(
                ids,
                new[]
            {
                new[] { 0, 1, 2, 3, 4 }
            },
                cache.UnlockMultipleCalls
                );
        }
示例#20
0
        public async Task TestOwnerAsync()
        {
            using (var session = OpenSession())
                using (var t = session.BeginTransaction())
                {
                    var entity = await(session.Query <Entity>().SingleAsync(e => e.Name == "Bob"));

                    // The Elements collection is mapped with a custom type which assert the owner
                    // is not null.
                    await(NHibernateUtil.InitializeAsync(entity.Elements));
                    Assert.That(entity.Elements, Has.Count.GreaterThan(0));
                    await(t.CommitAsync());
                }
        }
示例#21
0
        public async Task CachedCollectionRefreshAsync()
        {
            ISession         s    = OpenSession();
            Category         c    = new Category();
            IList <Category> list = new List <Category>();

            c.Subcategories = list;
            list.Add(new Category());
            c.Name = "root";
            object id = await(s.SaveAsync(c));

            await(s.FlushAsync());
            s.Close();

            s = OpenSession();
            c = (Category)await(s.LoadAsync(typeof(Category), id));
            await(NHibernateUtil.InitializeAsync(c.Subcategories));

            ISession ss = OpenSession();
            Category c2 = (Category)await(ss.LoadAsync(typeof(Category), id));

            await(ss.DeleteAsync(c2.Subcategories[0]));
            c2.Subcategories.Clear();
            await(ss.FlushAsync());
            ss.Close();

            await(s.RefreshAsync(c));
            Assert.AreEqual(0, c.Subcategories.Count);

            ss = OpenSession();
            c2 = (Category)await(ss.LoadAsync(typeof(Category), id));
            c2.Subcategories.Add(new Category());
            c2.Subcategories.Add(new Category());
            await(ss.FlushAsync());
            ss.Close();

            await(s.RefreshAsync(c));
            Assert.AreEqual(2, c.Subcategories.Count);

            await(s.FlushAsync());
            s.Close();

            s = OpenSession();
            c = (Category)await(s.LoadAsync(typeof(Category), id));
            Assert.AreEqual(2, c.Subcategories.Count);
            await(s.DeleteAsync(c));
            await(s.FlushAsync());
            s.Close();
        }
示例#22
0
        public async Task TestAsync()
        {
            using (ISession session = OpenSession())
            {
                using (session.BeginTransaction())
                {
                    var result = from e in session.Query <Entity>()
                                 where e.Name == "Bob"
                                 select e;
                    var entity = await(result.SingleAsync());

                    await(NHibernateUtil.InitializeAsync(entity.Children));
                }
            }
        }
示例#23
0
        public async Task PropertyLoadedNotInitializedAsync()
        {
            using (ISession s = OpenSession())
            {
                var book = await(s.LoadAsync <Book>(1));

                Assert.That(NHibernateUtil.IsPropertyInitialized(book, "Id"), Is.False);
                Assert.That(NHibernateUtil.IsPropertyInitialized(book, "Name"), Is.False);
                Assert.That(NHibernateUtil.IsPropertyInitialized(book, "ALotOfText"), Is.False);

                await(NHibernateUtil.InitializeAsync(book));

                Assert.That(NHibernateUtil.IsPropertyInitialized(book, "Id"), Is.True);
                Assert.That(NHibernateUtil.IsPropertyInitialized(book, "Name"), Is.True);
                Assert.That(NHibernateUtil.IsPropertyInitialized(book, "ALotOfText"), Is.False);
            }
        }
示例#24
0
        public async Task QueryWithLazyBaseClassShouldNotThrowNoPersisterForErrorAsync()
        {
            try
            {
                using (var s = OpenSession())
                    using (var t = s.BeginTransaction())
                    {
                        var item1 = new Derived
                        {
                            LongContent = "LongLongLongLongLong"
                        };
                        var root = new Root
                        {
                            Base = item1
                        };
                        await(s.SaveAsync(item1));
                        await(s.SaveAsync(root));
                        await(t.CommitAsync());
                    }

                // This will succeed if either:
                // a) we do not initialize root.Base
                // or
                // b) Base.LongContent is made non-lazy (remove lazy properties)

                using (var s = OpenSession())
                    using (var t = s.BeginTransaction())
                    {
                        var root = await(s.CreateQuery("from Root").UniqueResultAsync <Root>());
                        await(NHibernateUtil.InitializeAsync(root.Base));
                        var q = s.CreateQuery("from Derived d where d = ?")
                                .SetEntity(0, root.Base);
                        await(q.ListAsync());
                    }
            }
            finally
            {
                using (var s = OpenSession())
                    using (var t = s.BeginTransaction())
                    {
                        await(s.DeleteAsync("from Root"));
                        await(s.DeleteAsync("from Derived"));
                        await(t.CommitAsync());
                    }
            }
        }
        public async Task InitializedLazyManyToOneBeforeParentShouldNotBeAProxyAsync()
        {
            Order   order;
            Payment payment;

            using (var s = OpenSession())
            {
                payment = await(s.LoadAsync <Payment>(1));
                await(NHibernateUtil.InitializeAsync(payment));
                order = await(s.GetAsync <Order>(1));
                // Here the Payment property should be unwrapped
                payment = order.Payment;
            }

            Assert.That(order.Payment, Is.EqualTo(payment));
            Assert.That(order.Payment is WireTransfer, Is.True);
        }
示例#26
0
        public async Task WhereClauseInManyToOneNavigationAsync()
        {
            User inactive = new User();

            inactive.Id       = 10;
            inactive.Name     = "inactive";
            inactive.IsActive = 0;

            Employee employee = new Employee();

            employee.Id   = 20;
            employee.User = inactive;

            using (ISession s = OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    await(s.SaveAsync(inactive));
                    await(s.SaveAsync(employee));
                    await(t.CommitAsync());
                }

            using (ISession s = OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    Employee loaded = (Employee)await(s.GetAsync(typeof(Employee), employee.Id));
                    Assert.IsNotNull(loaded.User);

                    try
                    {
                        await(NHibernateUtil.InitializeAsync(loaded.User));
                        Assert.Fail("Should not have initialized");
                    }
                    catch (ObjectNotFoundException)
                    {
                        // Correct
                    }

                    await(s.DeleteAsync("from Employee"));
                    await(s.DeleteAsync("from User"));
                    await(t.CommitAsync());
                }
        }
示例#27
0
        /// <inheritdoc />
        public async ValueTask <Object> LoadAsync(EntityInfo entityInfo, CancellationToken token = default)
        {
            object maybeProxy = await session.GetAsync(entityInfo.Clazz, entityInfo.Id, token);

            // TODO: Initialize call and error trapping
            try
            {
                await NHibernateUtil.InitializeAsync(maybeProxy, token);
            }
            catch (Exception e)
            {
                if (!IsEntityNotFound(e, entityInfo))
                {
                    throw;
                }

                maybeProxy = null;
            }

            return(maybeProxy);
        }
示例#28
0
 public async Task MapAsync()
 {
     using (new MapScenario(Sfi))
         using (ISession s = OpenSession())
         {
             // for the case of <map> what really matter is the key, then NH should count the KEY and not the elements.
             using (ITransaction t = s.BeginTransaction())
             {
                 var entity = await(s.CreateQuery("from Parent").UniqueResultAsync <Parent>());
                 IList <object[]> members = await(s.GetNamedQuery("MapMemberSpy")
                                                  .SetParameter("parentid", entity.Id)
                                                  .ListAsync <object[]>());
                 int lazyCount = entity.MapChildren.Count;
                 Assert.That(NHibernateUtil.IsInitialized(entity.MapChildren), Is.False);
                 await(NHibernateUtil.InitializeAsync(entity.MapChildren));
                 int initCount = entity.MapChildren.Count;
                 Assert.That(initCount, Is.EqualTo(lazyCount));
                 Assert.That(members, Has.Count.EqualTo(3), "because all elements with a valid key should be persisted.");
             }
         }
 }
            public async Task <bool> OnPreUpdateAsync(PreUpdateEvent @event, CancellationToken cancellationToken)
            {
                Executed = true;
                Object[] oldValues  = @event.OldState;
                String[] properties = @event.Persister.PropertyNames;

                // Iterate through all fields of the updated object
                for (int i = 0; i < properties.Length; i++)
                {
                    if (oldValues != null && oldValues[i] != null)
                    {
                        if (!NHibernateUtil.IsInitialized(oldValues[i]))
                        {
                            // force any proxies and/or collections to initialize to illustrate HHH-2763
                            FoundAny = true;
                            await(NHibernateUtil.InitializeAsync(oldValues[i], cancellationToken));
                        }
                    }
                }
                return(true);
            }
        public async Task Getting_a_ManyA_object_with_fetchmode_select_will_workAsync()
        {
            ManyA loadedManyA;

            using (var session = OpenSession())
                using (var transaction = session.BeginTransaction())
                {
                    loadedManyA =
                        await(session
                              .CreateCriteria <ManyA>()
                              .Add(Restrictions.IdEq(_manyAId))
                              // Below Fetch is a no-op indeed, provided the mapping does not ask for eager fetching.
                              // It is the equivalent of obsoleted SetFetchMode Select, which was also no-op, contrary
                              // to what the SelectMode xml comment could let think. (This comment was valid only when
                              // the enum was used for mapping, but not when used ins queries.)
                              .Fetch(SelectMode.Skip, "ManyBs")
                              .UniqueResultAsync <ManyA>());
                    await(NHibernateUtil.InitializeAsync(loadedManyA.ManyBs));
                    await(transaction.CommitAsync());
                }

            /******************the select statements *************************************************************
             * SELECT	this_.Id as Id0_0_,
             *              this_.Number as Number0_0_,
             *              this_.Value as Value0_0_
             * FROM	ManyA this_
             * WHERE	this_.Id = 1 /# ?p0 /#
             *
             * SELECT	manybs0_.ManyBNumber as ManyBNum1_1_,
             *              manybs0_.ManyANumber as ManyANum2_1_,
             *              manyb1_.Id           as Id2_0_,
             *              manyb1_.Number       as Number2_0_,
             *              manyb1_.Value        as Value2_0_
             * FROM	ManyBs manybs0_
             * left outer join ManyB manyb1_ on manybs0_.ManyANumber = manyb1_.Number
             * WHERE  manybs0_.ManyBNumber =6 /# ?p0 #/
             */

            Assert.That(loadedManyA.ManyBs.Count, Is.EqualTo(3));
        }