private Predicate <object> CreateShouldSerialize(Type memberType, Predicate <object> currentPredicate, Func <object, object> getValue) { return(_entityMetadataProvider.IsEntityType(memberType) ? MergePredicates(currentPredicate, o => NHibernateUtil.IsInitialized(getValue(o))) : currentPredicate); }
public async Task MultipleCollectionFetchAsync() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Product p = new Product(); p.ProductId = "A123"; p.Description = "nipple ring"; p.Price = 1.0m; p.NumberAvailable = 1004; await(s.PersistAsync(p)); Product p2 = new Product(); p2.ProductId = "X525"; p2.Description = "nose stud"; p2.Price = 3.0m; p2.NumberAvailable = 105; await(s.PersistAsync(p2)); Customer c = new Customer(); c.Address = "St Kilda Rd, MEL, 3000"; c.Name = "Virginia"; c.CustomerId = "C111"; await(s.PersistAsync(c)); Order o = new Order(c); o.OrderDate = DateTime.Today; LineItem li = new LineItem(o, p); li.Quantity = 2; LineItem li2 = new LineItem(o, p2); li2.Quantity = 3; Order o2 = new Order(c); o2.OrderDate = DateTime.Today; LineItem li3 = new LineItem(o2, p); li3.Quantity = 1; LineItem li4 = new LineItem(o2, p2); li4.Quantity = 1; await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); c = (Customer) await(s.CreateQuery( "from Customer c left join fetch c.Orders o left join fetch o.LineItems li left join fetch li.Product p"). UniqueResultAsync()); Assert.IsTrue(NHibernateUtil.IsInitialized(c.Orders)); Assert.AreEqual(2, c.Orders.Count); Assert.IsTrue(NHibernateUtil.IsInitialized(((Order)c.Orders[0]).LineItems)); Assert.IsTrue(NHibernateUtil.IsInitialized(((Order)c.Orders[1]).LineItems)); Assert.AreEqual(((Order)c.Orders[0]).LineItems.Count, 2); Assert.AreEqual(((Order)c.Orders[1]).LineItems.Count, 2); await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); await(s.DeleteAsync("from LineItem")); await(s.DeleteAsync("from Order")); await(s.DeleteAsync("from Customer")); await(s.DeleteAsync("from Product")); await(t.CommitAsync()); s.Close(); }
public void MergeWithReadOnlyProxy() { DataPoint dp = null; using (ISession s = OpenSession()) { s.CacheMode = CacheMode.Ignore; using (ITransaction t = s.BeginTransaction()) { dp = new DataPoint(); dp.X = 0.1M; dp.Y = (decimal)System.Math.Cos((double)dp.X); s.Save(dp); t.Commit(); } } dp.Description = "description"; using (ISession s = OpenSession()) { s.CacheMode = CacheMode.Ignore; using (ITransaction t = s.BeginTransaction()) { s.DefaultReadOnly = true; DataPoint dpProxy = s.Load <DataPoint>(dp.Id); Assert.That(s.IsReadOnly(dpProxy), Is.True); Assert.That(NHibernateUtil.IsInitialized(dpProxy), Is.False); s.Evict(dpProxy); dpProxy = (DataPoint)s.Merge(dpProxy); Assert.That(s.IsReadOnly(dpProxy), Is.True); Assert.That(NHibernateUtil.IsInitialized(dpProxy), Is.False); dpProxy = (DataPoint)s.Merge(dp); Assert.That(s.IsReadOnly(dpProxy), Is.True); Assert.That(NHibernateUtil.IsInitialized(dpProxy), Is.True); Assert.That(dpProxy.Description, Is.EqualTo("description")); s.Evict(dpProxy); dpProxy = (DataPoint)s.Merge(dpProxy); Assert.That(s.IsReadOnly(dpProxy), Is.True); Assert.That(NHibernateUtil.IsInitialized(dpProxy), Is.True); Assert.That(dpProxy.Description, Is.EqualTo("description")); dpProxy.Description = null; dpProxy = (DataPoint)s.Merge(dp); Assert.That(s.IsReadOnly(dpProxy), Is.True); Assert.That(NHibernateUtil.IsInitialized(dpProxy), Is.True); Assert.That(dpProxy.Description, Is.EqualTo("description")); t.Commit(); } } using (ISession s = OpenSession()) { using (ITransaction t = s.BeginTransaction()) { dp = s.Get <DataPoint>(dp.Id); Assert.That(dp.Description, Is.Null); s.Delete(dp); t.Commit(); } } }
public void QueryCacheInvalidation() { sessions.EvictQueries(); sessions.Statistics.Clear(); const string queryString = "from Item i where i.Name='widget'"; object savedId = CreateItem(queryString); QueryStatistics qs = sessions.Statistics.GetQueryStatistics(queryString); EntityStatistics es = sessions.Statistics.GetEntityStatistics(typeof(Item).FullName); Thread.Sleep(200); IList result; using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { result = s.CreateQuery(queryString).SetCacheable(true).List(); Assert.That(result.Count, Is.EqualTo(1)); tx.Commit(); } Assert.That(qs.CacheHitCount, Is.EqualTo(0)); using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { result = s.CreateQuery(queryString).SetCacheable(true).List(); Assert.That(result.Count, Is.EqualTo(1)); tx.Commit(); } Assert.That(qs.CacheHitCount, Is.EqualTo(1)); Assert.That(es.FetchCount, Is.EqualTo(0)); using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { result = s.CreateQuery(queryString).SetCacheable(true).List(); Assert.That(result.Count, Is.EqualTo(1)); Assert.That(NHibernateUtil.IsInitialized(result[0])); var i = (Item)result[0]; i.Name = "Widget"; tx.Commit(); } Assert.That(qs.CacheHitCount, Is.EqualTo(2)); Assert.That(qs.CacheMissCount, Is.EqualTo(2)); Assert.That(es.FetchCount, Is.EqualTo(0)); Thread.Sleep(200); using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { s.CreateQuery(queryString).SetCacheable(true).List(); var i = s.Get <Item>(savedId); Assert.That(i.Name, Is.EqualTo("Widget")); s.Delete(i); tx.Commit(); } Assert.That(qs.CacheHitCount, Is.EqualTo(2)); Assert.That(qs.CacheMissCount, Is.EqualTo(3)); Assert.That(qs.CachePutCount, Is.EqualTo(3)); Assert.That(qs.ExecutionCount, Is.EqualTo(3)); Assert.That(es.FetchCount, Is.EqualTo(0)); //check that it was being cached }
public void UnionSubclassManyToOne() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Location mel = new Location("Melbourne, Australia"); Location mars = new Location("Mars"); s.Save(mel); s.Save(mars); Human gavin = new Human(); gavin.Identity = "gavin"; gavin.Sex = 'M'; gavin.Location = mel; mel.AddBeing(gavin); Alien x23y4 = new Alien(); x23y4.Identity = "x23y4$$hu%3"; x23y4.Location = mars; x23y4.Species = "martian"; mars.AddBeing(x23y4); Hive hive = new Hive(); hive.Location = mars; hive.Members.Add(x23y4); x23y4.Hive = hive; s.Persist(hive); Thing thing = new Thing(); thing.Description = "some thing"; thing.Owner = gavin; gavin.Things.Add(thing); s.Save(thing); s.Flush(); s.Clear(); thing = (Thing)s.CreateQuery("from Thing t left join fetch t.owner").UniqueResult(); Assert.IsTrue(NHibernateUtil.IsInitialized(thing.Owner)); Assert.AreEqual("gavin", thing.Owner.Identity); s.Clear(); thing = (Thing)s.CreateQuery("select t from Thing t left join t.owner where t.owner.identity='gavin'").UniqueResult(); Assert.IsFalse(NHibernateUtil.IsInitialized(thing.Owner)); Assert.AreEqual("gavin", thing.Owner.Identity); s.Clear(); gavin = (Human)s.CreateQuery("from Human h left join fetch h.things").UniqueResult(); Assert.IsTrue(NHibernateUtil.IsInitialized(gavin.Things)); Assert.AreEqual("some thing", ((Thing)gavin.Things[0]).Description); s.Clear(); Assert.AreEqual(2, s.CreateQuery("from Being b left join fetch b.things").List().Count); s.Clear(); gavin = (Human)s.CreateQuery("from Being b join fetch b.things").UniqueResult(); Assert.IsTrue(NHibernateUtil.IsInitialized(gavin.Things)); Assert.AreEqual("some thing", ((Thing)gavin.Things[0]).Description); s.Clear(); gavin = (Human)s.CreateQuery("select h from Human h join h.things t where t.description='some thing'").UniqueResult(); Assert.IsFalse(NHibernateUtil.IsInitialized(gavin.Things)); Assert.AreEqual("some thing", ((Thing)gavin.Things[0]).Description); s.Clear(); gavin = (Human)s.CreateQuery("select b from Being b join b.things t where t.description='some thing'").UniqueResult(); Assert.IsFalse(NHibernateUtil.IsInitialized(gavin.Things)); Assert.AreEqual("some thing", ((Thing)gavin.Things[0]).Description); s.Clear(); thing = s.Get <Thing>(thing.Id); Assert.IsFalse(NHibernateUtil.IsInitialized(thing.Owner)); Assert.AreEqual("gavin", thing.Owner.Identity); thing.Owner.Things.Remove(thing); thing.Owner = x23y4; x23y4.Things.Add(thing); s.Flush(); s.Clear(); thing = s.Get <Thing>(thing.Id); Assert.IsFalse(NHibernateUtil.IsInitialized(thing.Owner)); Assert.AreEqual("x23y4$$hu%3", thing.Owner.Identity); s.Delete(thing); x23y4 = (Alien)s.CreateCriteria(typeof(Alien)).UniqueResult(); s.Delete(x23y4.Hive); s.Delete(s.Get <Location>(mel.Id)); s.Delete(s.Get <Location>(mars.Id)); Assert.AreEqual(0, s.CreateQuery("from Being").List().Count); t.Commit(); s.Close(); }
public static void ShouldBeLazy(this object proxy) { NHibernateUtil.IsInitialized(proxy).ShouldBeFalse(); }
private static void AssertFetchManyToOneAndComponentManyToOne(Person person) { AssertFetchComponentManyToOne(person); Assert.That(NHibernateUtil.IsInitialized(person.BestFriend), Is.True); }
private void UpdateChildrenDependencies(int batchNumber, AbstractEntityInsertAction action) { var propertyValues = action.State; var propertyTypes = action.Persister.EntityMetamodel?.PropertyTypes; if (propertyTypes == null) { log.Warn( "Entity {0} persister does not provide meta-data: if there is dependent entities providing " + "meta-data, they may get batched before this one and cause a failure.", action.EntityName); return; } var sessionFactory = action.Session.Factory; for (var i = 0; i < propertyValues.Length; i++) { var type = propertyTypes[i]; if (!type.IsCollectionType) { continue; } var collectionType = (CollectionType)type; var collectionPersister = sessionFactory.GetCollectionPersister(collectionType.Role); if (collectionPersister.IsManyToMany || !collectionPersister.ElementType.IsEntityType) { continue; } var children = propertyValues[i] as IEnumerable; if (children == null) { continue; } foreach (var child in children) { if (child == null || // If the child is not initialized, it is a proxy with pending load from database, // so it can only be an already persisted entity. It can not have its own pending // insertion batch. So we do not need to keep track of the highest other batch on // which it depends. And this avoids initializing the proxy by searching it into // a dictionary. !NHibernateUtil.IsInitialized(child)) { continue; } int latestDependency; if (_entityBatchDependency.TryGetValue(child, out latestDependency) && latestDependency > batchNumber) { continue; } _entityBatchDependency[child] = batchNumber; } } }
public void FullCream() { object savedCustomerId; // Test saving these proxies using (var session = sessions.OpenSession()) { session.BeginTransaction(); var company = entityFactory.NewEntity <ICompany>(); company.Name = "acme"; session.Save(company); var customer = entityFactory.NewEntity <ICustomer>(); customer.Name = "Katsumoto"; customer.Company = company; var address = entityFactory.NewEntity <IAddress>(); address.Street = "somewhere over the rainbow"; address.City = "lawerence, kansas"; address.PostalCode = "toto"; customer.Address = address; customer.Family = new HashedSet <IPerson>(); var son = entityFactory.NewEntity <IPerson>(); son.Name = "son"; customer.Family.Add(son); var wife = entityFactory.NewEntity <IPerson>(); wife.Name = "wife"; customer.Family.Add(wife); savedCustomerId = session.Save(customer); session.Transaction.Commit(); Assert.IsNotNull(company.Id, "company id not assigned"); Assert.IsNotNull(customer.Id, "customer id not assigned"); Assert.IsNotNull(address.Id, "address id not assigned"); Assert.IsNotNull(son.Id, "son:Person id not assigned"); Assert.IsNotNull(wife.Id, "wife:Person id not assigned"); } // Test loading these proxies, along with flush processing ICustomer willDetached; using (var session = sessions.OpenSession()) { session.BeginTransaction(); willDetached = session.Load <ICustomer>(savedCustomerId); Assert.IsFalse(NHibernateUtil.IsInitialized(willDetached), "should-be-proxy was initialized"); willDetached.Name = "other"; session.Flush(); Assert.IsFalse(NHibernateUtil.IsInitialized(willDetached.Company), "should-be-proxy was initialized"); session.Refresh(willDetached); Assert.AreEqual("other", willDetached.Name, "name not updated"); Assert.AreEqual("acme", willDetached.Company.Name, "company association not correct"); session.Transaction.Commit(); } // Test detached entity re-attachment with these dyna-proxies willDetached.Name = "Katsumoto"; //<= is detached using (var session = sessions.OpenSession()) { session.BeginTransaction(); session.Update(willDetached); session.Flush(); session.Refresh(willDetached); Assert.AreEqual("Katsumoto", willDetached.Name, "name not updated"); session.Transaction.Commit(); } // Test querying using (var session = sessions.OpenSession()) { session.BeginTransaction(); int count = session.CreateQuery("from ICustomer").List().Count; Assert.AreEqual(1, count, "querying dynamic entity"); session.Clear(); count = session.CreateQuery("from IPerson").List().Count; Assert.AreEqual(3, count, "querying dynamic entity"); session.Transaction.Commit(); } // test deleteing using (var session = sessions.OpenSession()) using (var tx = session.BeginTransaction()) { session.Delete("from ICompany"); session.Delete("from ICustomer"); tx.Commit(); } }
public async Task ShouldWorkLoadingComplexEntitiesAsync() { const string crocodileFather = "Crocodile father"; const string crocodileMother = "Crocodile mother"; using (ISession s = Sfi.OpenSession()) using (ITransaction tx = s.BeginTransaction()) { var rf = new Reptile { Description = crocodileFather }; var rm = new Reptile { Description = crocodileMother }; var rc1 = new Reptile { Description = "Crocodile" }; var rc2 = new Reptile { Description = "Crocodile" }; var rfamily = new Family <Reptile> { Father = rf, Mother = rm, Childs = new HashSet <Reptile> { rc1, rc2 } }; await(s.SaveAsync("ReptilesFamily", rfamily)); await(tx.CommitAsync()); } const string humanFather = "Fred"; const string humanMother = "Wilma"; using (ISession s = Sfi.OpenSession()) using (ITransaction tx = s.BeginTransaction()) { var hf = new Human { Description = "Flinstone", Name = humanFather }; var hm = new Human { Description = "Flinstone", Name = humanMother }; var hc1 = new Human { Description = "Flinstone", Name = "Pebbles" }; var hfamily = new Family <Human> { Father = hf, Mother = hm, Childs = new HashSet <Human> { hc1 } }; await(s.SaveAsync("HumanFamily", hfamily)); await(tx.CommitAsync()); } using (IStatelessSession s = Sfi.OpenStatelessSession()) using (ITransaction tx = s.BeginTransaction()) { IList <Family <Human> > hf = await(s.CreateQuery("from HumanFamily").ListAsync <Family <Human> >()); Assert.That(hf.Count, Is.EqualTo(1)); Assert.That(hf[0].Father.Name, Is.EqualTo(humanFather)); Assert.That(hf[0].Mother.Name, Is.EqualTo(humanMother)); Assert.That(NHibernateUtil.IsInitialized(hf[0].Childs), Is.True, "No lazy collection should be initialized"); //Assert.That(hf[0].Childs, Is.Null, "Collections should be ignored by stateless session."); IList <Family <Reptile> > rf = await(s.CreateQuery("from ReptilesFamily").ListAsync <Family <Reptile> >()); Assert.That(rf.Count, Is.EqualTo(1)); Assert.That(rf[0].Father.Description, Is.EqualTo(crocodileFather)); Assert.That(rf[0].Mother.Description, Is.EqualTo(crocodileMother)); Assert.That(NHibernateUtil.IsInitialized(hf[0].Childs), Is.True, "No lazy collection should be initialized"); //Assert.That(rf[0].Childs, Is.Null, "Collections should be ignored by stateless session."); await(tx.CommitAsync()); } using (ISession s = Sfi.OpenSession()) using (ITransaction tx = s.BeginTransaction()) { await(s.DeleteAsync("from HumanFamily")); await(s.DeleteAsync("from ReptilesFamily")); await(tx.CommitAsync()); } }
public void TestCreateQuery() { var cust = new Customer(); cust.CustomerId = "abc123"; cust.Name = "Matt"; var ship = new Address(); ship.Street = "peachtree rd"; ship.State = "GA"; ship.City = "ATL"; ship.Zip = "30326"; ship.AddressId = new AddressId("SHIPPING", "xyz123"); ship.Customer = cust; var bill = new Address(); bill.Street = "peachtree rd"; bill.State = "GA"; bill.City = "ATL"; bill.Zip = "30326"; bill.AddressId = new AddressId("BILLING", "xyz123"); bill.Customer = cust; cust.BillingAddress = bill; cust.ShippingAddress = ship; using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { s.Persist(cust); t.Commit(); } using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { IList results = s.CreateQuery("from Customer cust left join fetch cust.BillingAddress where cust.CustomerId='abc123'").List(); //IList results = s.CreateQuery("from Customer cust left join fetch cust.BillingAddress left join fetch cust.ShippingAddress").List(); cust = (Customer)results[0]; Assert.That(NHibernateUtil.IsInitialized(cust.ShippingAddress), Is.False); Assert.That(NHibernateUtil.IsInitialized(cust.BillingAddress), Is.True); Assert.That(cust.BillingAddress.Zip, Is.EqualTo("30326")); Assert.That(cust.ShippingAddress.Zip, Is.EqualTo("30326")); Assert.That(cust.BillingAddress.AddressId.Type, Is.EqualTo("BILLING")); Assert.That(cust.ShippingAddress.AddressId.Type, Is.EqualTo("SHIPPING")); t.Commit(); } using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { s.SaveOrUpdate(cust); ship = cust.ShippingAddress; cust.ShippingAddress = null; s.Delete("ShippingAddress", ship); s.Flush(); Assert.That(s.Get("ShippingAddress", ship.AddressId), Is.Null); s.Delete(cust); t.Commit(); } }
public void UnionSubclass() { using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { Employee mark = new Employee(); mark.Name = "Mark"; mark.Title = "internal sales"; mark.Sex = 'M'; mark.Address.address = "buckhead"; mark.Address.zip = "30305"; mark.Address.country = "USA"; Customer joe = new Customer(); joe.Name = "Joe"; joe.Address.address = "San Francisco"; joe.Address.zip = "XXXXX"; joe.Address.country = "USA"; joe.Comments = "Very demanding"; joe.Sex = 'M'; joe.Salesperson = mark; Person yomomma = new Person(); yomomma.Name = "mum"; yomomma.Sex = 'F'; s.Save(yomomma); s.Save(mark); s.Save(joe); // TODO NH : This line is present in H3.2.5 test; ReadCommitted ? //Assert.AreEqual(0, s.CreateQuery("from System.Object").List().Count); Assert.AreEqual(3, s.CreateQuery("from Person").List().Count); Assert.AreEqual(1, s.CreateQuery("from Person p where p.class = Customer").List().Count); Assert.AreEqual(1, s.CreateQuery("from Person p where p.class = Person").List().Count); s.Clear(); IList <Customer> customers = s.CreateQuery("from Customer c left join fetch c.salesperson").List <Customer>(); foreach (Customer c in customers) { Assert.IsTrue(NHibernateUtil.IsInitialized(c.Salesperson)); Assert.AreEqual("Mark", c.Salesperson.Name); } Assert.AreEqual(1, customers.Count); s.Clear(); customers = s.CreateQuery("from Customer").List <Customer>(); foreach (Customer c in customers) { Assert.IsFalse(NHibernateUtil.IsInitialized(c.Salesperson)); Assert.AreEqual("Mark", c.Salesperson.Name); } Assert.AreEqual(1, customers.Count); s.Clear(); mark = s.Get <Employee>(mark.Id); joe = s.Get <Customer>(joe.Id); mark.Address.zip = "30306"; Assert.AreEqual(1, s.CreateQuery("from Person p where p.address.zip = '30306'").List().Count); s.Delete(mark); s.Delete(joe); s.Delete(yomomma); Assert.AreEqual(0, s.CreateQuery("from Person").List().Count); t.Commit(); s.Close(); } }
public async Task ItAsync() { var company = ProxyHelper.NewCompanyProxy(); var customer = ProxyHelper.NewCustomerProxy(); // Test saving these dyna-proxies using (var session = OpenSession()) using (var tran = session.BeginTransaction()) { company.Name = "acme"; await(session.SaveAsync(company)); customer.Name = "Steve"; customer.Company = company; await(session.SaveAsync(customer)); await(tran.CommitAsync()); session.Close(); } Assert.IsNotNull(company.Id, "company id not assigned"); Assert.IsNotNull(customer.Id, "customer id not assigned"); // Test loading these dyna-proxies, along with flush processing using (var session = OpenSession()) using (var tran = session.BeginTransaction()) { customer = await(session.LoadAsync <Customer>(customer.Id)); Assert.IsFalse(NHibernateUtil.IsInitialized(customer), "should-be-proxy was initialized"); customer.Name = "other"; await(session.FlushAsync()); Assert.IsFalse(NHibernateUtil.IsInitialized(customer.Company), "should-be-proxy was initialized"); await(session.RefreshAsync(customer)); Assert.AreEqual("other", customer.Name, "name not updated"); Assert.AreEqual("acme", customer.Company.Name, "company association not correct"); await(tran.CommitAsync()); session.Close(); } // Test detached entity re-attachment with these dyna-proxies customer.Name = "Steve"; using (var session = OpenSession()) using (var tran = session.BeginTransaction()) { await(session.UpdateAsync(customer)); await(session.FlushAsync()); await(session.RefreshAsync(customer)); Assert.AreEqual("Steve", customer.Name, "name not updated"); await(tran.CommitAsync()); session.Close(); } // Test querying using (var session = OpenSession()) using (var tran = session.BeginTransaction()) { int count = (await(session.CreateQuery("from Customer").ListAsync())).Count; Assert.AreEqual(1, count, "querying dynamic entity"); session.Clear(); count = (await(session.CreateQuery("from Person").ListAsync())).Count; Assert.AreEqual(1, count, "querying dynamic entity"); await(tran.CommitAsync()); session.Close(); } // test deleteing using (var session = OpenSession()) using (var tran = session.BeginTransaction()) { await(session.DeleteAsync(company)); await(session.DeleteAsync(customer)); await(tran.CommitAsync()); session.Close(); } }
private static Predicate <object> CreateShouldSerializeForAssociationProperty(Func <object, object> getPropertyValueFunction) { return(entity => NHibernateUtil.IsInitialized(getPropertyValueFunction(entity))); }
public async Task ProxyReuseAsync() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); FooProxy foo = new Foo(); FooProxy foo2 = new Foo(); object id = await(s.SaveAsync(foo)); object id2 = await(s.SaveAsync(foo2)); foo2.Int = 1234567; foo.Int = 1234; await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); foo = (FooProxy)await(s.LoadAsync(typeof(Foo), id)); foo2 = (FooProxy)await(s.LoadAsync(typeof(Foo), id2)); Assert.IsFalse(NHibernateUtil.IsInitialized(foo)); await(NHibernateUtil.InitializeAsync(foo2)); await(NHibernateUtil.InitializeAsync(foo)); Assert.AreEqual(3, foo.Component.ImportantDates.Length); Assert.AreEqual(3, foo2.Component.ImportantDates.Length); await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); foo.Float = 1.2f; foo2.Float = 1.3f; foo2.Dependent.Key = null; foo2.Component.Subcomponent.Fee.Key = null; Assert.IsFalse(foo2.Key.Equals(id)); await(s.SaveAsync(foo, "xyzid")); await(s.UpdateAsync(foo2, id)); //intentionally id, not id2! Assert.AreEqual(id, foo2.Key); Assert.AreEqual(1234567, foo2.Int); Assert.AreEqual("xyzid", foo.Key); await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); foo = (FooProxy)await(s.LoadAsync(typeof(Foo), id)); Assert.AreEqual(1234567, foo.Int); Assert.AreEqual(3, foo.Component.ImportantDates.Length); await(s.DeleteAsync(foo)); await(s.DeleteAsync(await(s.GetAsync(typeof(Foo), id2)))); await(s.DeleteAsync(await(s.GetAsync(typeof(Foo), "xyzid")))); Assert.AreEqual(3, await(s.DeleteAsync("from System.Object"))); await(t.CommitAsync()); s.Close(); string feekey = foo.Dependent.Key; s = OpenSession(); t = s.BeginTransaction(); foo.Component.Glarch = null; //no id property! await(s.ReplicateAsync(foo, ReplicationMode.Overwrite)); await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); Foo refoo = (Foo)await(s.GetAsync(typeof(Foo), id)); Assert.AreEqual(feekey, refoo.Dependent.Key); await(s.DeleteAsync(refoo)); await(t.CommitAsync()); s.Close(); }
public void ShouldWorkLoadingComplexEntities() { const string crocodileFather = "Crocodile father"; const string crocodileMother = "Crocodile mother"; using (ISession s = sessions.OpenSession()) using (ITransaction tx = s.BeginTransaction()) { var rf = new Reptile { Description = crocodileFather }; var rm = new Reptile { Description = crocodileMother }; var rc1 = new Reptile { Description = "Crocodile" }; var rc2 = new Reptile { Description = "Crocodile" }; var rfamily = new Family <Reptile> { Father = rf, Mother = rm, Childs = new HashedSet <Reptile> { rc1, rc2 } }; s.Save("ReptileFamily", rfamily); tx.Commit(); } const string humanFather = "Fred"; const string humanMother = "Wilma"; using (ISession s = sessions.OpenSession()) using (ITransaction tx = s.BeginTransaction()) { var hf = new Human { Description = "Flinstone", Name = humanFather }; var hm = new Human { Description = "Flinstone", Name = humanMother }; var hc1 = new Human { Description = "Flinstone", Name = "Pebbles" }; var hfamily = new Family <Human> { Father = hf, Mother = hm, Childs = new HashedSet <Human> { hc1 } }; s.Save("HumanFamily", hfamily); tx.Commit(); } using (IStatelessSession s = sessions.OpenStatelessSession()) using (ITransaction tx = s.BeginTransaction()) { IList <Family <Human> > hf = s.CreateQuery("from HumanFamily").List <Family <Human> >(); Assert.That(hf.Count, Is.EqualTo(1)); Assert.That(hf[0].Father.Name, Is.EqualTo(humanFather)); Assert.That(hf[0].Mother.Name, Is.EqualTo(humanMother)); NHibernateUtil.IsInitialized(hf[0].Childs).Should("Lazy collection should NOT be initialized").Be.False(); IList <Family <Reptile> > rf = s.CreateQuery("from ReptileFamily").List <Family <Reptile> >(); Assert.That(rf.Count, Is.EqualTo(1)); Assert.That(rf[0].Father.Description, Is.EqualTo(crocodileFather)); Assert.That(rf[0].Mother.Description, Is.EqualTo(crocodileMother)); NHibernateUtil.IsInitialized(hf[0].Childs).Should("Lazy collection should NOT be initialized").Be.False(); tx.Commit(); } using (ISession s = sessions.OpenSession()) using (ITransaction tx = s.BeginTransaction()) { s.Delete("from HumanFamily"); s.Delete("from ReptileFamily"); tx.Commit(); } }
public async Task ComplexCriteriaAsync() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Baz baz = new Baz(); await(s.SaveAsync(baz)); baz.SetDefaults(); IDictionary <char, GlarchProxy> topGlarchez = new Dictionary <char, GlarchProxy>(); baz.TopGlarchez = topGlarchez; Glarch g1 = new Glarch(); g1.Name = "g1"; await(s.SaveAsync(g1)); Glarch g2 = new Glarch(); g2.Name = "g2"; await(s.SaveAsync(g2)); g1.ProxyArray = new GlarchProxy[] { g2 }; topGlarchez['1'] = g1; topGlarchez['2'] = g2; Foo foo1 = new Foo(); Foo foo2 = new Foo(); await(s.SaveAsync(foo1)); await(s.SaveAsync(foo2)); baz.FooSet.Add(foo1); baz.FooSet.Add(foo2); baz.FooArray = new FooProxy[] { foo1 }; LockMode lockMode = (Dialect is DB2Dialect) ? LockMode.Read : LockMode.Upgrade; ICriteria crit = s.CreateCriteria(typeof(Baz)); crit.CreateCriteria("TopGlarchez") .Add(Expression.IsNotNull("Name")) .CreateCriteria("ProxyArray") .Add(Expression.EqProperty("Name", "Name")) .Add(Expression.Eq("Name", "g2")) .Add(Expression.Gt("X", -666)); crit.CreateCriteria("FooSet") .Add(Expression.IsNull("Null")) .Add(Expression.Eq("String", "a string")) .Add(Expression.Lt("Integer", -665)); crit.CreateCriteria("FooArray") .Add(Expression.Eq("String", "a string")) .SetLockMode(lockMode); IList list = await(crit.ListAsync()); Assert.AreEqual(2, list.Count); await(s.CreateCriteria(typeof(Glarch)).SetLockMode(LockMode.Upgrade).ListAsync()); await(s.CreateCriteria(typeof(Glarch)).SetLockMode(CriteriaSpecification.RootAlias, LockMode.Upgrade).ListAsync()); g2.Name = null; await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); crit = s.CreateCriteria(typeof(Baz)) .SetLockMode(lockMode); crit.CreateCriteria("TopGlarchez") .Add(Expression.Gt("X", -666)); crit.CreateCriteria("FooSet") .Add(Expression.IsNull("Null")); list = await(crit.ListAsync()); Assert.AreEqual(4, list.Count); baz = (Baz)await(crit.UniqueResultAsync()); Assert.IsTrue(NHibernateUtil.IsInitialized(baz.TopGlarchez)); //cos it is nonlazy Assert.IsFalse(NHibernateUtil.IsInitialized(baz.FooSet)); //list = s.CreateCriteria(typeof( Baz )) // .createCriteria("fooSet.foo.component.glarch") // .Add( Expression.eq("name", "xxx") ) // .Add( Expression.eq("fooSet.foo.component.glarch.name", "xxx") ) // .list(); //assertTrue( list.size()==0 ); list = await(s.CreateCriteria(typeof(Baz)) .CreateCriteria("FooSet") .CreateCriteria("TheFoo") .CreateCriteria("Component.Glarch") .Add(Expression.Eq("Name", "xxx")) .ListAsync()); Assert.AreEqual(0, list.Count); list = await(s.CreateCriteria(typeof(Baz)) .CreateAlias("FooSet", "foo") .CreateAlias("foo.TheFoo", "foo2") .SetLockMode("foo2", lockMode) .Add(Expression.IsNull("foo2.Component.Glarch")) .CreateCriteria("foo2.Component.Glarch") .Add(Expression.Eq("Name", "xxx")) .ListAsync()); Assert.AreEqual(0, list.Count); await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); crit = s.CreateCriteria(typeof(Baz)); crit.CreateCriteria("TopGlarchez") .Add(Expression.IsNotNull("Name")); crit.CreateCriteria("FooSet") .Add(Expression.IsNull("Null")); list = await(crit.ListAsync()); Assert.AreEqual(2, list.Count); baz = (Baz)await(crit.UniqueResultAsync()); Assert.IsTrue(NHibernateUtil.IsInitialized(baz.TopGlarchez)); //cos it is nonlazy Assert.IsFalse(NHibernateUtil.IsInitialized(baz.FooSet)); await(s.DeleteAsync("from Glarch g")); await(s.DeleteAsync(await(s.GetAsync(typeof(Foo), foo1.Key)))); await(s.DeleteAsync(await(s.GetAsync(typeof(Foo), foo2.Key)))); await(s.DeleteAsync(baz)); await(t.CommitAsync()); s.Close(); }
public async Task WhereAndOrderByReuseJoinsAsync() { OrderLine orderLine; using (var logSpy = new SqlLogSpy()) { orderLine = (await(db.OrderLines .Where(o => o.Order.Customer.ContactName == "Maria Anders") .OrderBy(o => o.Order.Customer.ContactName) .Fetch(o => o.Order).ThenFetch(o => o.Customer) .ToListAsync())) .First(); var sql = logSpy.GetWholeLog(); Assert.That(GetTotalOccurrences(sql, "join"), Is.EqualTo(2)); Assert.That(GetTotalOccurrences(sql, "inner join"), Is.EqualTo(2)); Assert.That(NHibernateUtil.IsInitialized(orderLine.Order), Is.True); Assert.That(NHibernateUtil.IsInitialized(orderLine.Order.Customer), Is.True); } session.Clear(); using (var logSpy = new SqlLogSpy()) { orderLine = (await(db.OrderLines .Where(o => o.Order.Customer.ContactName == "Maria Anders") .OrderBy(o => o.Order.Customer.ContactName) .Fetch(o => o.Order) .ToListAsync())) .First(); var sql = logSpy.GetWholeLog(); Assert.That(GetTotalOccurrences(sql, "join"), Is.EqualTo(2)); Assert.That(GetTotalOccurrences(sql, "inner join"), Is.EqualTo(2)); Assert.That(NHibernateUtil.IsInitialized(orderLine.Order), Is.True); Assert.That(NHibernateUtil.IsInitialized(orderLine.Order.Customer), Is.False); } using (var logSpy = new SqlLogSpy()) { (await(db.Employees .Where(o => o.Superior.Superior.Superior.FirstName != null) .OrderBy(o => o.Superior.Superior.Superior.FirstName) .Fetch(o => o.Superior) .ToListAsync())) .FirstOrDefault(); var sql = logSpy.GetWholeLog(); Assert.That(GetTotalOccurrences(sql, ","), Is.EqualTo(31), "Only the first level should be fetched."); Assert.That(GetTotalOccurrences(sql, "join"), Is.EqualTo(3)); Assert.That(GetTotalOccurrences(sql, "inner join"), Is.EqualTo(3)); } using (var logSpy = new SqlLogSpy()) { (await(db.Employees .Where(o => o.Superior.FirstName != null) .OrderBy(o => o.Superior.FirstName) .Fetch(o => o.Superior).ThenFetch(o => o.Superior).ThenFetch(o => o.Superior) .ToListAsync())) .FirstOrDefault(); var sql = logSpy.GetWholeLog(); Assert.That(GetTotalOccurrences(sql, "join"), Is.EqualTo(3)); Assert.That(GetTotalOccurrences(sql, "inner join"), Is.EqualTo(1)); Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(2)); } }
public override void Validate( LegalEntity legalEntity ) { Assert.That(NHibernateUtil.IsInitialized(legalEntity.Country)); }
public void CompositeIdJoinsFailureExpected() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Person person = new Person(); person.Name = "Noob"; Product product = new Product(); product.ProductId = new Product.ProductIdType(); product.ProductId.Orgid = "x"; product.ProductId.Productnumber = "1234"; product.Name = "Hibernate 3"; Order order = new Order(); order.OrderId = new Order.OrderIdType(); order.OrderId.Ordernumber = "1"; order.OrderId.Orgid = "y"; product.Orders.Add(order); order.Product = product; order.Person = person; s.Save(product); s.Save(order); s.Save(person); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); Product p = (Product)s.CreateQuery("from Product p join fetch p.orders").List()[0]; Assert.IsTrue(NHibernateUtil.IsInitialized(p.Orders)); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); object[] o = (object[])s.CreateSQLQuery( "select\r\n" + " product.orgid as {product.id.orgid}," + " product.productnumber as {product.id.productnumber}," + " {prod_orders}.orgid as orgid3_1_,\r\n" + " {prod_orders}.ordernumber as ordernum2_3_1_,\r\n" + " product.name as {product.name}," + " {prod_orders.element.*}," + /*" orders.PROD_NO as PROD4_3_1_,\r\n" + * " orders.person as person3_1_,\r\n" + * " orders.PROD_ORGID as PROD3_0__,\r\n" + * " orders.PROD_NO as PROD4_0__,\r\n" + * " orders.orgid as orgid0__,\r\n" + * " orders.ordernumber as ordernum2_0__ \r\n" +*/ " from\r\n" + " Product product \r\n" + " inner join\r\n" + " TBL_ORDER {prod_orders} \r\n" + " on product.orgid={prod_orders}.PROD_ORGID \r\n" + " and product.productnumber={prod_orders}.PROD_NO") .AddEntity("product", typeof(Product)) .AddJoin("prod_orders", "product.orders") .List()[0]; p = (Product)o[0]; Assert.IsTrue(NHibernateUtil.IsInitialized(p.Orders)); IEnumerator en = p.Orders.GetEnumerator(); Assert.IsTrue(en.MoveNext()); Assert.IsNotNull(en.Current); t.Commit(); s.Close(); }
public void MasterDetail() { //if( dialect is Dialect.HSQLDialect ) return; ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Master master = new Master(); Assert.IsNotNull(s.Save(master), "save returned native id"); object mid = s.GetIdentifier(master); Detail d1 = new Detail(); d1.Master = master; object did = s.Save(d1); Detail d2 = new Detail(); d2.I = 12; d2.Master = master; Assert.IsNotNull(s.Save(d2), "generated id returned"); master.AddDetail(d1); master.AddDetail(d2); if (Dialect.SupportsSubSelects) { string hql = "from d in class NHibernate.DomainModel.Detail, m in class NHibernate.DomainModel.Master " + "where m = d.Master and m.Outgoing.size = 0 and m.Incoming.size = 0"; Assert.AreEqual(2, s.CreateQuery(hql).List().Count, "query"); } t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); master = (Master)s.Load(typeof(Master), mid); IEnumerator enumer = master.Details.GetEnumerator(); int i = 0; while (enumer.MoveNext()) { Detail d = (Detail)enumer.Current; Assert.AreSame(master, d.Master, "master-detail"); i++; } Assert.AreEqual(2, i, "master-detail count"); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); Assert.AreEqual(2, s.CreateQuery("select elements(master.Details) from Master master").List().Count); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); IList list = s.CreateQuery("from Master m left join fetch m.Details").List(); Master m = (Master)list[0]; Assert.IsTrue(NHibernateUtil.IsInitialized(m.Details), "joined fetch should initialize collection"); Assert.AreEqual(2, m.Details.Count); list = s.CreateQuery("from Detail d inner join fetch d.Master").List(); Detail dt = (Detail)list[0]; object dtid = s.GetIdentifier(dt); Assert.AreSame(m, dt.Master); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); list = s.CreateQuery("select m from Master m1, Master m left join fetch m.Details where m.Name=m1.Name").List(); Assert.IsTrue(NHibernateUtil.IsInitialized(((Master)list[0]).Details)); dt = (Detail)s.Load(typeof(Detail), dtid); Assert.IsTrue(((Master)list[0]).Details.Contains(dt)); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); list = s.CreateQuery("select m, m1.Name from Master m1, Master m left join fetch m.Details where m.Name=m1.Name").List(); Master masterFromHql = (Master)((object[])list[0])[0]; Assert.IsTrue(NHibernateUtil.IsInitialized(masterFromHql.Details)); dt = (Detail)s.Load(typeof(Detail), dtid); Assert.IsTrue(masterFromHql.Details.Contains(dt)); // This line is commentend in H3.2 tests because it work in the classic parser // even if it as no sense ('join fetch' where the 'select' is a scalar) // The AST check the case with an Exception //list = s.CreateQuery("select m.id from Master m inner join fetch m.Details").List(); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); Detail dd = (Detail)s.Load(typeof(Detail), did); master = dd.Master; Assert.IsTrue(master.Details.Contains(dd), "detail-master"); Assert.AreEqual(2, s.CreateFilter(master.Details, "order by this.I desc").List().Count); Assert.AreEqual(2, s.CreateFilter(master.Details, "select this where this.id > -1").List().Count); IQuery q = s.CreateFilter(master.Details, "where this.id > :id"); q.SetInt32("id", -1); Assert.AreEqual(2, q.List().Count); q = s.CreateFilter(master.Details, "where this.id > :id1 and this.id < :id2"); q.SetInt32("id1", -1); q.SetInt32("id2", 99999999); Assert.AreEqual(2, q.List().Count); q.SetInt32("id2", -1); Assert.AreEqual(0, q.List().Count); q = s.CreateFilter(master.Details, "where this.id in (:ids)"); list = new ArrayList(); list.Add(did); list.Add((long)-1); q.SetParameterList("ids", list); Assert.AreEqual(1, q.List().Count); Assert.IsTrue(q.Enumerable().GetEnumerator().MoveNext()); Assert.AreEqual(2, s.CreateFilter(master.Details, "where this.id > -1").List().Count); Assert.AreEqual(2, s.CreateFilter(master.Details, "select this.Master where this.id > -1").List().Count); Assert.AreEqual(2, s.CreateFilter(master.Details, "select m from m in class Master where this.id > -1 and this.Master=m") .List().Count); Assert.AreEqual(0, s.CreateFilter(master.Incoming, "where this.id > -1 and this.Name is not null").List().Count); IQuery filter = s.CreateFilter(master.Details, "select max(this.I)"); enumer = filter.Enumerable().GetEnumerator(); Assert.IsTrue(enumer.MoveNext()); Assert.IsTrue(enumer.Current is Int32); filter = s.CreateFilter(master.Details, "select max(this.I) group by this.id"); enumer = filter.Enumerable().GetEnumerator(); Assert.IsTrue(enumer.MoveNext()); Assert.IsTrue(enumer.Current is Int32); filter = s.CreateFilter(master.Details, "select count(*)"); enumer = filter.Enumerable().GetEnumerator(); Assert.IsTrue(enumer.MoveNext()); Assert.IsTrue(enumer.Current is Int64); Assert.AreEqual(2, s.CreateFilter(master.Details, "select this.Master").List().Count); IQuery f = s.CreateFilter(master.Details, "select max(this.I) where this.I < :top and this.I>=:bottom"); f.SetInt32("top", 100); f.SetInt32("bottom", 0); enumer = f.Enumerable().GetEnumerator(); Assert.IsTrue(enumer.MoveNext()); Assert.AreEqual(12, enumer.Current); f.SetInt32("top", 2); enumer = f.Enumerable().GetEnumerator(); Assert.IsTrue(enumer.MoveNext()); Assert.AreEqual(0, enumer.Current); f = s.CreateFilter(master.Details, "select max(this.I) where this.I not in (:list)"); IList coll = new ArrayList(); coll.Add(-666); coll.Add(22); coll.Add(0); f.SetParameterList("list", coll); enumer = f.Enumerable().GetEnumerator(); Assert.IsTrue(enumer.MoveNext()); Assert.AreEqual(12, enumer.Current); i = 0; foreach (Detail d in master.Details) { Assert.AreSame(master, d.Master, "master-detail"); s.Delete(d); i++; } Assert.AreEqual(2, i, "master-detail"); s.Delete(master); t.Commit(); s.Close(); }
public void TestJoinedSubclass() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Employee mark = new Employee(); mark.Name = "Mark"; mark.Title = "internal sales"; mark.Sex = 'M'; mark.Address.Street = "buckhead"; mark.Address.Zip = "30305"; mark.Address.Country = "USA"; Customer joe = new Customer(); joe.Name = "Joe"; joe.Address.Street = "San Francisco"; joe.Address.Zip = "54353"; joe.Address.Country = "USA"; joe.Comments = "very demanding"; joe.Sex = 'M'; joe.Salesperson = mark; Person mom = new Person(); mom.Name = "mom"; mom.Sex = 'F'; s.Save(mom); s.Save(mark); s.Save(joe); Assert.AreEqual(3, s.CreateQuery("from Person").List().Count); IQuery query = s.CreateQuery("from Customer"); IList results = query.List(); Assert.AreEqual(1, results.Count); Assert.IsTrue(results[0] is Customer, "should be a customer"); s.Clear(); IList customers = s.CreateQuery("from Customer c left join fetch c.Salesperson").List(); foreach (Customer c in customers) { // when proxies is working this is important Assert.IsTrue(NHibernateUtil.IsInitialized(c.Salesperson)); Assert.AreEqual("Mark", c.Salesperson.Name); } Assert.AreEqual(1, customers.Count); s.Clear(); customers = s.CreateQuery("from Customer").List(); foreach (Customer c in customers) { Assert.IsFalse(NHibernateUtil.IsInitialized(c.Salesperson)); Assert.AreEqual("Mark", c.Salesperson.Name); } Assert.AreEqual(1, customers.Count); s.Clear(); mark = (Employee)s.Load(typeof(Employee), mark.Id); joe = (Customer)s.Load(typeof(Customer), joe.Id); mark.Address.Zip = "30306"; Assert.AreEqual(1, s.CreateQuery("from Person p where p.Address.Zip = '30306'").List().Count); s.Delete(mom); s.Delete(joe); s.Delete(mark); Assert.AreEqual(0, s.CreateQuery("from Person").List().Count); t.Commit(); s.Close(); }
public void UnionSubclassOneToMany() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Location mel = new Location("Melbourne, Australia"); Location mars = new Location("Mars"); s.Save(mel); s.Save(mars); Human gavin = new Human(); gavin.Identity = "gavin"; gavin.Sex = 'M'; gavin.Location = mel; mel.AddBeing(gavin); Alien x23y4 = new Alien(); x23y4.Identity = "x23y4$$hu%3"; x23y4.Location = mars; x23y4.Species = "martian"; mars.AddBeing(x23y4); Alien yy3dk = new Alien(); yy3dk.Identity = "yy3dk&*!!!"; yy3dk.Location = mars; yy3dk.Species = "martian"; mars.AddBeing(yy3dk); Hive hive = new Hive(); hive.Location = mars; hive.Members.Add(x23y4); x23y4.Hive = hive; hive.Members.Add(yy3dk); yy3dk.Hive = hive; s.Persist(hive); yy3dk.Hivemates.Add(x23y4); x23y4.Hivemates.Add(yy3dk); s.Flush(); s.Clear(); hive = (Hive)s.CreateQuery("from Hive h").UniqueResult(); Assert.IsFalse(NHibernateUtil.IsInitialized(hive.Members)); Assert.AreEqual(2, hive.Members.Count); s.Clear(); hive = (Hive)s.CreateQuery("from Hive h left join fetch h.location left join fetch h.members").UniqueResult(); Assert.IsTrue(NHibernateUtil.IsInitialized(hive.Members)); Assert.AreEqual(2, hive.Members.Count); s.Clear(); x23y4 = (Alien)s.CreateQuery("from Alien a left join fetch a.hivemates where a.identity like 'x%'").UniqueResult(); Assert.IsTrue(NHibernateUtil.IsInitialized(x23y4.Hivemates)); Assert.AreEqual(1, x23y4.Hivemates.Count); s.Clear(); x23y4 = (Alien)s.CreateQuery("from Alien a where a.identity like 'x%'").UniqueResult(); Assert.IsFalse(NHibernateUtil.IsInitialized(x23y4.Hivemates)); Assert.AreEqual(1, x23y4.Hivemates.Count); s.Clear(); x23y4 = (Alien)s.CreateCriteria(typeof(Alien)).AddOrder(Order.Asc("identity")).List()[0]; s.Delete(x23y4.Hive); s.Delete(s.Get <Location>(mel.Id)); s.Delete(s.Get <Location>(mars.Id)); Assert.IsTrue(s.CreateQuery("from Being").List().Count == 0); t.Commit(); s.Close(); }
public void Subclassing() { C1 c1; using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { c1 = new C1(); D d = new D(); d.Amount = 213.34f; c1.Address = "foo bar"; c1.Count = 23432; c1.Name = "c1"; c1.D = d; s.Save(c1); d.Id = c1.Id; s.Save(d); t.Commit(); } using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { // Test won't run after this line because of proxy initalization problems A c1a = (A)s.Load(typeof(A), c1.Id); Assert.IsFalse(NHibernateUtil.IsInitialized(c1a)); Assert.IsTrue(c1a.Name.Equals("c1")); t.Commit(); } using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { B c1b = (B)s.Load(typeof(B), c1.Id); Assert.IsTrue( (c1b.Count == 23432) && c1b.Name.Equals("c1") ); t.Commit(); } using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { c1 = (C1)s.Load(typeof(C1), c1.Id); Assert.IsTrue( c1.Address.Equals("foo bar") && (c1.Count == 23432) && c1.Name.Equals("c1") && c1.D.Amount > 213.3f ); t.Commit(); } using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { A c1a = (A)s.Load(typeof(A), c1.Id); Assert.IsTrue(c1a.Name.Equals("c1")); c1 = (C1)s.Load(typeof(C1), c1.Id); Assert.IsTrue( c1.Address.Equals("foo bar") && (c1.Count == 23432) && c1.Name.Equals("c1") && c1.D.Amount > 213.3f ); B c1b = (B)s.Load(typeof(B), c1.Id); Assert.IsTrue( (c1b.Count == 23432) && c1b.Name.Equals("c1") ); Assert.IsTrue(c1a.Name.Equals("c1")); t.Commit(); } using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { A c1a = (A)s.Load(typeof(A), c1.Id); Assert.IsTrue(c1a.Name.Equals("c1")); c1 = (C1)s.Load(typeof(C1), c1.Id, LockMode.Upgrade); Assert.IsTrue( c1.Address.Equals("foo bar") && (c1.Count == 23432) && c1.Name.Equals("c1") && c1.D.Amount > 213.3f ); B c1b = (B)s.Load(typeof(B), c1.Id, LockMode.Upgrade); Assert.IsTrue( (c1b.Count == 23432) && c1b.Name.Equals("c1") ); Assert.IsTrue(c1a.Name.Equals("c1")); t.Commit(); } using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { A c1a = (A)s.Load(typeof(A), c1.Id); c1 = (C1)s.Load(typeof(C1), c1.Id); B c1b = (B)s.Load(typeof(B), c1.Id); Assert.IsTrue(c1a.Name.Equals("c1")); Assert.IsTrue( c1.Address.Equals("foo bar") && (c1.Count == 23432) && c1.Name.Equals("c1") && c1.D.Amount > 213.3f ); Assert.IsTrue( (c1b.Count == 23432) && c1b.Name.Equals("c1") ); Console.Out.WriteLine(s.Delete("from a in class A")); t.Commit(); } using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { s.Save(new B()); s.Save(new A()); Assert.IsTrue(s.CreateQuery("from b in class B").List().Count == 1); Assert.IsTrue(s.CreateQuery("from a in class A").List().Count == 2); s.Delete("from a in class A"); s.Delete(c1.D); t.Commit(); } }
public void UnionSubclass() { using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { Location mel = new Location("Melbourne, Australia"); Location atl = new Location("Atlanta, GA"); Location mars = new Location("Mars"); s.Save(mel); s.Save(atl); s.Save(mars); Human gavin = new Human(); gavin.Identity = "gavin"; gavin.Sex = 'M'; gavin.Location = mel; mel.AddBeing(gavin); Alien x23y4 = new Alien(); x23y4.Identity = "x23y4$$hu%3"; x23y4.Location = mars; x23y4.Species = "martian"; mars.AddBeing(x23y4); Hive hive = new Hive(); hive.Location = mars; hive.Members.Add(x23y4); x23y4.Hive = hive; s.Persist(hive); Assert.AreEqual(2, s.CreateQuery("from Being").List().Count); Assert.AreEqual(1, s.CreateQuery("from Being b where b.class = Alien").List().Count); Assert.AreEqual(1, s.CreateQuery("from Alien").List().Count); s.Clear(); IList <Being> beings = s.CreateQuery("from Being b left join fetch b.location").List <Being>(); foreach (Being b in beings) { Assert.IsTrue(NHibernateUtil.IsInitialized(b.Location)); Assert.IsNotNull(b.Location.Name); Assert.IsNotNull(b.Identity); Assert.IsNotNull(b.Species); } Assert.AreEqual(2, beings.Count); s.Clear(); beings = s.CreateQuery("from Being").List <Being>(); foreach (Being b in beings) { Assert.IsFalse(NHibernateUtil.IsInitialized(b.Location)); Assert.IsNotNull(b.Location.Name); Assert.IsNotNull(b.Identity); Assert.IsNotNull(b.Species); } Assert.AreEqual(2, beings.Count); s.Clear(); IList <Location> locations = s.CreateQuery("from Location").List <Location>(); int count = 0; foreach (Location l in locations) { Assert.IsNotNull(l.Name); foreach (Being o in l.Beings) { count++; Assert.AreSame(o.Location, l); } } Assert.AreEqual(2, count); Assert.AreEqual(3, locations.Count); s.Clear(); locations = s.CreateQuery("from Location loc left join fetch loc.beings").List <Location>(); count = 0; foreach (Location l in locations) { Assert.IsNotNull(l.Name); foreach (Being o in l.Beings) { count++; Assert.AreSame(o.Location, l); } } Assert.AreEqual(2, count); Assert.AreEqual(3, locations.Count); s.Clear(); gavin = s.Get <Human>(gavin.Id); atl = s.Get <Location>(atl.Id); atl.AddBeing(gavin); Assert.AreEqual(1, s.CreateQuery("from Human h where h.location.name like '%GA'").List().Count); s.Delete(gavin); x23y4 = (Alien)s.CreateCriteria(typeof(Alien)).UniqueResult(); s.Delete(x23y4.Hive); Assert.AreEqual(0, s.CreateQuery("from Being").List().Count); t.Commit(); s.Close(); } using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { s.Delete("from Location"); t.Commit(); } }
public void SubselectFetchCriteria() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Parent p = new Parent("foo"); p.Children.Add(new Child("foo1")); p.Children.Add(new Child("foo2")); Parent q = new Parent("bar"); q.Children.Add(new Child("bar1")); q.Children.Add(new Child("bar2")); ArrayHelper.AddAll(q.MoreChildren, p.Children); s.Save(p); s.Save(q); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); Sfi.Statistics.Clear(); IList parents = s.CreateCriteria(typeof(Parent)) .Add(Expression.Between("Name", "bar", "foo")) .AddOrder(Order.Desc("Name")) .List(); p = (Parent)parents[0]; q = (Parent)parents[1]; Assert.IsFalse(NHibernateUtil.IsInitialized(p.Children)); Assert.IsFalse(NHibernateUtil.IsInitialized(q.Children)); Assert.AreEqual(p.Children.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(p.Children[0])); Assert.IsTrue(NHibernateUtil.IsInitialized(q.Children)); Assert.AreEqual(q.Children.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(q.Children[0])); Assert.IsFalse(NHibernateUtil.IsInitialized(p.MoreChildren)); Assert.IsFalse(NHibernateUtil.IsInitialized(q.MoreChildren)); Assert.AreEqual(p.MoreChildren.Count, 0); Assert.IsTrue(NHibernateUtil.IsInitialized(q.MoreChildren)); Assert.AreEqual(q.MoreChildren.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(q.MoreChildren[0])); Assert.AreEqual(3, Sfi.Statistics.PrepareStatementCount); Child c = (Child)p.Children[0]; NHibernateUtil.Initialize(c.Friends); s.Delete(p); s.Delete(q); t.Commit(); s.Close(); }
public async Task NonLazyFetchAsync() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Product p = new Product(); p.ProductId = "A123"; p.Description = "nipple ring"; p.Price = 1.0m; p.NumberAvailable = 1004; await(s.PersistAsync(p)); Product p2 = new Product(); p2.ProductId = "X525"; p2.Description = "nose stud"; p2.Price = 3.0m; p2.NumberAvailable = 105; await(s.PersistAsync(p2)); Customer c = new Customer(); c.Address = "St Kilda Rd, MEL, 3000"; c.Name = "Virginia"; c.CustomerId = "C111"; await(s.PersistAsync(c)); Order o = new Order(c); o.OrderDate = DateTime.Today; LineItem li = new LineItem(o, p); li.Quantity = 2; await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); o = await(s.GetAsync <Order>(new Order.ID("C111", 0))); Assert.AreEqual(2m, o.Total); await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); o = (Order)await(s.CreateQuery("from Order o left join fetch o.LineItems li left join fetch li.Product p").UniqueResultAsync()); Assert.IsTrue(NHibernateUtil.IsInitialized(o.LineItems)); li = (LineItem)o.LineItems[0]; Assert.IsTrue(NHibernateUtil.IsInitialized(li)); Assert.IsTrue(NHibernateUtil.IsInitialized(li.Product)); await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); o = (Order)await(s.CreateQuery("from Order o").UniqueResultAsync()); Assert.IsTrue(NHibernateUtil.IsInitialized(o.LineItems)); li = (LineItem)o.LineItems[0]; Assert.IsTrue(NHibernateUtil.IsInitialized(li)); Assert.IsFalse(NHibernateUtil.IsInitialized(li.Product)); await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); await(s.DeleteAsync("from LineItem")); await(s.DeleteAsync("from Order")); await(s.DeleteAsync("from Customer")); await(s.DeleteAsync("from Product")); await(t.CommitAsync()); s.Close(); }
public void SubselectFetchNamedParam() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Parent p = new Parent("foo"); p.Children.Add(new Child("foo1")); p.Children.Add(new Child("foo2")); Parent q = new Parent("bar"); q.Children.Add(new Child("bar1")); q.Children.Add(new Child("bar2")); ArrayHelper.AddAll(q.MoreChildren, p.Children); s.Save(p); s.Save(q); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); Sfi.Statistics.Clear(); IList parents = s.CreateQuery("from Parent where name between :bar and :foo order by name desc") .SetParameter("bar", "bar") .SetParameter("foo", "foo") .List(); p = (Parent)parents[0]; q = (Parent)parents[1]; Assert.IsFalse(NHibernateUtil.IsInitialized(p.Children)); Assert.IsFalse(NHibernateUtil.IsInitialized(q.Children)); Assert.AreEqual(p.Children.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(p.Children[0])); Assert.IsTrue(NHibernateUtil.IsInitialized(q.Children)); Assert.AreEqual(q.Children.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(q.Children[0])); Assert.IsFalse(NHibernateUtil.IsInitialized(p.MoreChildren)); Assert.IsFalse(NHibernateUtil.IsInitialized(q.MoreChildren)); Assert.AreEqual(p.MoreChildren.Count, 0); Assert.IsTrue(NHibernateUtil.IsInitialized(q.MoreChildren)); Assert.AreEqual(q.MoreChildren.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(q.MoreChildren[0])); Assert.AreEqual(3, Sfi.Statistics.PrepareStatementCount); Child c = (Child)p.Children[0]; NHibernateUtil.Initialize(c.Friends); s.Delete(p); s.Delete(q); t.Commit(); s.Close(); }
public void ReadOnlyProxyRefreshDetached() { DataPoint dp = null; using (ISession s = OpenSession()) { s.CacheMode = CacheMode.Ignore; using (ITransaction t = s.BeginTransaction()) { dp = new DataPoint(); dp.Description = "original"; dp.X = 0.1M; dp.Y = (decimal)System.Math.Cos((double)dp.X); s.Save(dp); t.Commit(); } } using (ISession s = OpenSession()) { s.CacheMode = CacheMode.Ignore; using (ITransaction t = s.BeginTransaction()) { s.DefaultReadOnly = true; dp = s.Load <DataPoint>(dp.Id); Assert.That(NHibernateUtil.IsInitialized(dp), Is.False); Assert.That(s.IsReadOnly(dp), Is.True); s.Evict(dp); s.Refresh(dp); Assert.That(NHibernateUtil.IsInitialized(dp), Is.False); s.DefaultReadOnly = false; Assert.That(s.IsReadOnly(dp), Is.True); s.Evict(dp); s.Refresh(dp); Assert.That(NHibernateUtil.IsInitialized(dp), Is.False); Assert.That(s.IsReadOnly(dp), Is.False); Assert.That(s.IsReadOnly(((INHibernateProxy)dp).HibernateLazyInitializer.GetImplementation()), Is.False); dp.Description = "changed"; Assert.That(dp.Description, Is.EqualTo("changed")); Assert.That(NHibernateUtil.IsInitialized(dp), Is.True); s.Evict(dp); s.Refresh(dp); Assert.That(dp.Description, Is.EqualTo("original")); Assert.That(s.IsReadOnly(dp), Is.False); Assert.That(s.IsReadOnly(((INHibernateProxy)dp).HibernateLazyInitializer.GetImplementation()), Is.False); dp.Description = "changed"; Assert.That(dp.Description, Is.EqualTo("changed")); s.DefaultReadOnly = true; s.Evict(dp); s.Refresh(dp); Assert.That(dp.Description, Is.EqualTo("original")); Assert.That(s.IsReadOnly(dp), Is.True); Assert.That(s.IsReadOnly(((INHibernateProxy)dp).HibernateLazyInitializer.GetImplementation()), Is.True); dp.Description = "changed"; Assert.That(dp.Description, Is.EqualTo("changed")); t.Commit(); } s.Clear(); using (ITransaction t = s.BeginTransaction()) { dp = s.Get <DataPoint>(dp.Id); Assert.That(dp.Description, Is.EqualTo("original")); s.Delete(dp); t.Commit(); } } }
public async Task SubselectFetchHqlAsync() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Parent p = new Parent("foo"); p.Children.Add(new Child("foo1")); p.Children.Add(new Child("foo2")); Parent q = new Parent("bar"); q.Children.Add(new Child("bar1")); q.Children.Add(new Child("bar2")); ArrayHelper.AddAll(q.MoreChildren, p.Children); await(s.SaveAsync(p)); await(s.SaveAsync(q)); await(t.CommitAsync()); s.Close(); s = OpenSession(); t = s.BeginTransaction(); Sfi.Statistics.Clear(); IList parents = await(s.CreateQuery("from Parent where name between 'bar' and 'foo' order by name desc") .ListAsync()); p = (Parent)parents[0]; q = (Parent)parents[1]; Assert.IsFalse(NHibernateUtil.IsInitialized(p.Children)); Assert.IsFalse(NHibernateUtil.IsInitialized(q.Children)); Assert.AreEqual(p.Children.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(p.Children[0])); Assert.IsTrue(NHibernateUtil.IsInitialized(q.Children)); Assert.AreEqual(q.Children.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(q.Children[0])); Assert.IsFalse(NHibernateUtil.IsInitialized(p.MoreChildren)); Assert.IsFalse(NHibernateUtil.IsInitialized(q.MoreChildren)); Assert.AreEqual(p.MoreChildren.Count, 0); Assert.IsTrue(NHibernateUtil.IsInitialized(q.MoreChildren)); Assert.AreEqual(q.MoreChildren.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(q.MoreChildren[0])); Assert.AreEqual(3, Sfi.Statistics.PrepareStatementCount); Child c = (Child)p.Children[0]; await(NHibernateUtil.InitializeAsync(c.Friends)); await(s.DeleteAsync(p)); await(s.DeleteAsync(q)); await(t.CommitAsync()); s.Close(); }