private string GetEntityName(IQuerySource querySource) { return(NHibernateUtil.Entity(querySource.ItemType).Name); }
private static Predicate <object> CreateShouldSerializeForAssociationProperty(Func <object, object> getPropertyValueFunction) { return(entity => NHibernateUtil.IsInitialized(getPropertyValueFunction(entity))); }
public void GuessType() { Assert.That(NHibernateUtil.GuessType(typeof(DateTime)), Is.EqualTo(_testDefaultDateTimeType)); }
public void UpdateBasicProperties(ArtistForEditContract properties, PictureDataContract pictureData, IUserPermissionContext permissionContext) { ParamIs.NotNull(() => properties); ParamIs.NotNull(() => permissionContext); HandleTransaction(session => { var artist = session.Load <Artist>(properties.Id); VerifyEntryEdit(artist); var diff = new ArtistDiff(DoSnapshot(artist.GetLatestVersion(), GetLoggedUser(session))); SysLog(string.Format("updating properties for {0}", artist)); if (artist.ArtistType != properties.ArtistType) { artist.ArtistType = properties.ArtistType; diff.ArtistType = true; } if (artist.Description != properties.Description) { artist.Description = properties.Description; diff.Description = true; } if (artist.TranslatedName.DefaultLanguage != properties.TranslatedName.DefaultLanguage) { artist.TranslatedName.DefaultLanguage = properties.TranslatedName.DefaultLanguage; diff.OriginalName = true; } NHibernateUtil.Initialize(artist.Picture); if (pictureData != null) { artist.Picture = new PictureData(pictureData); diff.Picture = true; } if (artist.Status != properties.Status) { artist.Status = properties.Status; diff.Status = true; } var nameDiff = artist.Names.Sync(properties.Names.AllNames, artist); SessionHelper.Sync(session, nameDiff); if (nameDiff.Changed) { diff.Names = true; } var validWebLinks = properties.WebLinks.Where(w => !string.IsNullOrEmpty(w.Url)); var webLinkDiff = WebLink.Sync(artist.WebLinks, validWebLinks, artist); SessionHelper.Sync(session, webLinkDiff); if (webLinkDiff.Changed) { diff.WebLinks = true; } if (diff.ArtistType || diff.Names) { foreach (var song in artist.Songs) { song.Song.UpdateArtistString(); session.Update(song); } } var groupsDiff = CollectionHelper.Diff(artist.Groups, properties.Groups, (i, i2) => (i.Id == i2.Id)); foreach (var grp in groupsDiff.Removed) { grp.Delete(); session.Delete(grp); } foreach (var grp in groupsDiff.Added) { var link = artist.AddGroup(session.Load <Artist>(grp.Group.Id)); session.Save(link); } if (groupsDiff.Changed) { diff.Groups = true; } var picsDiff = artist.Pictures.SyncPictures(properties.Pictures, GetLoggedUser(session), artist.CreatePicture); SessionHelper.Sync(session, picsDiff); ImageHelper.GenerateThumbsAndMoveImages(picsDiff.Added); if (picsDiff.Changed) { diff.Pictures = true; } /* * var albumGetter = new Func<AlbumForArtistEditContract, Album>(contract => { * * Album album; * * if (contract.AlbumId != 0) { * * album = session.Load<Album>(contract.AlbumId); * * } else { * * AuditLog(string.Format("creating a new album '{0}' to {1}", contract.AlbumName, artist)); * * album = new Album(contract.AlbumName); * session.Save(album); * * Services.Albums.Archive(session, album, AlbumArchiveReason.Created, * string.Format("Created for artist '{0}'", artist.DefaultName)); * * AuditLog(string.Format("created {0} for {1}", * EntryLinkFactory.CreateEntryLink(album), EntryLinkFactory.CreateEntryLink(artist)), session); * AddEntryEditedEntry(session, album, EntryEditEvent.Created); * * } * * return album; * * }); * * if (properties.AlbumLinks != null * && !properties.TooManyAlbums * && (properties.AlbumLinks.Any() || artist.Albums.Count() < ArtistForEditContract.MaxAlbums / 2) * && artist.Albums.Count() <= ArtistForEditContract.MaxAlbums) { * * var albumDiff = artist.SyncAlbums(properties.AlbumLinks, albumGetter); * * SessionHelper.Sync(session, albumDiff); * * if (albumDiff.Changed) { * * diff.Albums = true; * * var add = string.Join(", ", albumDiff.Added.Select(i => i.Album.ToString())); * var rem = string.Join(", ", albumDiff.Removed.Select(i => i.Album.ToString())); * * var str = string.Format("edited albums (added: {0}, removed: {1})", add, rem) * .Truncate(300); * * AuditLog(str, session); * * } * * }*/ var logStr = string.Format("updated properties for {0} ({1})", EntryLinkFactory.CreateEntryLink(artist), diff.ChangedFieldsString) + (properties.UpdateNotes != string.Empty ? " " + properties.UpdateNotes : string.Empty) .Truncate(400); AuditLog(logStr, session); AddEntryEditedEntry(session, artist, EntryEditEvent.Updated); Archive(session, artist, diff, ArtistArchiveReason.PropertiesUpdated, properties.UpdateNotes); session.Update(artist); return(true); }); }
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 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 async Task SubselectFetchNamedParamAsync() { 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") .SetParameter("bar", "bar") .SetParameter("foo", "foo") .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(); }
public IQuery SetEnum(string name, Enum val) { SetParameter(name, val, NHibernateUtil.Enum(val.GetType())); return(this); }
public void Test() { int a_id; using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { // Create an A and save it ClassA a = new ClassA(); a.Name = "a1"; s.Save(a); // Create a B and save it ClassB b = new ClassB(); b.Id = new ClassBId("bbb", a); b.SomeProp = "Some property"; s.Save(b); // Create a C and save it ClassC c = new ClassC(); c.B = b; s.Save(c); tx.Commit(); a_id = a.Id; } // Clear the cache sessions.Evict(typeof(ClassA)); sessions.Evict(typeof(ClassB)); sessions.Evict(typeof(ClassC)); using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { // Load a so we can use it to load b ClassA a = s.Get <ClassA>(a_id); // Load b so b will be in cache ClassB b = s.Get <ClassB>(new ClassBId("bbb", a)); tx.Commit(); } using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { using (SqlLogSpy sqlLogSpy = new SqlLogSpy()) { IList <ClassC> c_list = s.CreateCriteria(typeof(ClassC)).List <ClassC>(); // make sure we initialize B NHibernateUtil.Initialize(c_list[0].B); Assert.AreEqual(1, sqlLogSpy.Appender.GetEvents().Length, "Only one SQL should have been issued"); } tx.Commit(); } }
public IQuery SetEnum(int position, Enum val) { SetParameter(position, val, NHibernateUtil.Enum(val.GetType())); return(this); }
public IQuery SetEntity(string name, object val) { SetParameter(name, val, NHibernateUtil.Entity(NHibernateProxyHelper.GuessClass(val))); return(this); }
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.SupportsScalarSubSelects) { 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)"); q.SetParameterList("ids", new[] { did, (long)-1 }); 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)"); f.SetParameterList("list", new List <int> { -666, 22, 0 }); 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 ToStringWithNoIdentifier() { NHibernateUtil.Entity(typeof(Master)).ToLoggableString(new Master(), (ISessionFactoryImplementor)Sfi); }
public async Task <int> Update(ArtistForEditContract properties, EntryPictureFileContract pictureData, IUserPermissionContext permissionContext) { ParamIs.NotNull(() => properties); ParamIs.NotNull(() => permissionContext); return(await repository.HandleTransactionAsync(async ctx => { var artist = await ctx.LoadAsync(properties.Id); VerifyEntryEdit(artist); var diff = new ArtistDiff(DoSnapshot(artist.GetLatestVersion(), await ctx.OfType <User>().GetLoggedUserAsync(permissionContext))); ctx.AuditLogger.SysLog(string.Format("updating properties for {0}", artist)); if (artist.ArtistType != properties.ArtistType) { artist.ArtistType = properties.ArtistType; diff.ArtistType.Set(); } diff.Description.Set(artist.Description.CopyFrom(properties.Description)); if (artist.TranslatedName.DefaultLanguage != properties.DefaultNameLanguage) { artist.TranslatedName.DefaultLanguage = properties.DefaultNameLanguage; diff.OriginalName.Set(); } // Required because of a bug in NHibernate NHibernateUtil.Initialize(artist.Picture); if (pictureData != null) { var parsed = ImageHelper.GetOriginal(pictureData.UploadedFile, pictureData.ContentLength, pictureData.Mime); artist.Picture = new PictureData(parsed); artist.PictureMime = parsed.Mime; pictureData.Id = artist.Id; pictureData.EntryType = EntryType.Artist; var thumbGenerator = new ImageThumbGenerator(imagePersister); thumbGenerator.GenerateThumbsAndMoveImage(pictureData.UploadedFile, pictureData, ImageSizes.Thumb | ImageSizes.SmallThumb | ImageSizes.TinyThumb); diff.Picture.Set(); } if (artist.Status != properties.Status) { artist.Status = properties.Status; diff.Status.Set(); } var nameDiff = artist.Names.Sync(properties.Names, artist); await ctx.OfType <ArtistName>().SyncAsync(nameDiff); if (nameDiff.Changed) { diff.Names.Set(); } if (!artist.BaseVoicebank.NullSafeIdEquals(properties.BaseVoicebank)) { var newBase = await ctx.NullSafeLoadAsync(properties.BaseVoicebank); if (artist.IsValidBaseVoicebank(newBase)) { diff.BaseVoicebank.Set(); artist.SetBaseVoicebank(await ctx.NullSafeLoadAsync(properties.BaseVoicebank)); } } if (!artist.ReleaseDate.Equals(properties.ReleaseDate)) { artist.ReleaseDate = properties.ReleaseDate; diff.ReleaseDate.Set(); } var webLinkDiff = WebLink.Sync(artist.WebLinks, properties.WebLinks, artist); await ctx.OfType <ArtistWebLink>().SyncAsync(webLinkDiff); if (webLinkDiff.Changed) { diff.WebLinks.Set(); } if (diff.ArtistType.IsChanged || diff.Names.IsChanged || diff.OriginalName.IsChanged) { foreach (var song in artist.Songs) { song.Song.UpdateArtistString(); await ctx.UpdateAsync(song); } } var newGroups = properties.Groups .Select(g => new ArtistForArtistContract { Parent = g.Parent, LinkType = ArtistLinkType.Group }) .Concat(new[] { new ArtistForArtistContract { Parent = properties.Illustrator, LinkType = ArtistLinkType.Illustrator }, new ArtistForArtistContract { Parent = properties.VoiceProvider, LinkType = ArtistLinkType.VoiceProvider } }) .Concat(properties.AssociatedArtists) .Where(a => a.Parent != null && ArtistHelper.CanHaveRelatedArtists(artist.ArtistType, a.LinkType, LinkDirection.ManyToOne)) .ToArray(); var groupsDiff = CollectionHelper.Diff(artist.Groups, newGroups, (i, i2) => (i.Parent.Id == i2.Parent.Id && i.LinkType == i2.LinkType)); foreach (var grp in groupsDiff.Removed) { grp.Delete(); await ctx.DeleteAsync(grp); } foreach (var grp in groupsDiff.Added) { var link = artist.AddGroup(ctx.Load(grp.Parent.Id), grp.LinkType); await ctx.SaveAsync(link); } if (groupsDiff.Changed) { diff.Groups.Set(); } var picsDiff = artist.Pictures.SyncPictures(properties.Pictures, ctx.OfType <User>().GetLoggedUser(permissionContext), artist.CreatePicture); ctx.OfType <ArtistPictureFile>().Sync(picsDiff); var entryPictureFileThumbGenerator = new ImageThumbGenerator(pictureFilePersister); artist.Pictures.GenerateThumbsAndMoveImage(entryPictureFileThumbGenerator, picsDiff.Added, ImageSizes.Original | ImageSizes.Thumb); if (picsDiff.Changed) { diff.Pictures.Set(); } var logStr = string.Format("updated properties for artist {0} ({1})", entryLinkFactory.CreateEntryLink(artist), diff.ChangedFieldsString) + (properties.UpdateNotes != string.Empty ? " " + properties.UpdateNotes : string.Empty) .Truncate(400); var archived = await ArchiveAsync(ctx, artist, diff, ArtistArchiveReason.PropertiesUpdated, properties.UpdateNotes); await ctx.UpdateAsync(artist); await ctx.AuditLogger.AuditLogAsync(logStr); await AddEntryEditedEntryAsync(ctx.OfType <ActivityEntry>(), artist, EntryEditEvent.Updated, archived); return artist.Id; })); }
public void NonLazyFetch() { 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; s.Persist(p); Product p2 = new Product(); p2.ProductId = "X525"; p2.Description = "nose stud"; p2.Price = 3.0m; p2.NumberAvailable = 105; s.Persist(p2); Customer c = new Customer(); c.Address = "St Kilda Rd, MEL, 3000"; c.Name = "Virginia"; c.CustomerId = "C111"; s.Persist(c); Order o = new Order(c); o.OrderDate = DateTime.Today; LineItem li = new LineItem(o, p); li.Quantity = 2; t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); o = s.Get <Order>(new Order.ID("C111", 0)); Assert.AreEqual(2m, o.Total); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); o = (Order)s.CreateQuery("from Order o left join fetch o.LineItems li left join fetch li.Product p").UniqueResult(); Assert.IsTrue(NHibernateUtil.IsInitialized(o.LineItems)); li = (LineItem)o.LineItems[0]; Assert.IsTrue(NHibernateUtil.IsInitialized(li)); Assert.IsTrue(NHibernateUtil.IsInitialized(li.Product)); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); o = (Order)s.CreateQuery("from Order o").UniqueResult(); Assert.IsTrue(NHibernateUtil.IsInitialized(o.LineItems)); li = (LineItem)o.LineItems[0]; Assert.IsTrue(NHibernateUtil.IsInitialized(li)); Assert.IsFalse(NHibernateUtil.IsInitialized(li.Product)); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); s.Delete("from LineItem"); s.Delete("from Order"); s.Delete("from Customer"); s.Delete("from Product"); t.Commit(); s.Close(); }
public override bool Equals(object obj) { Book book = (Book)obj; if ( (NHibernateUtil.IsInitialized(book.authors) && this.authors.SequenceEqual(book.authors)) || !NHibernateUtil.IsInitialized(book.authors) && this.book_name.Equals(book.book_name) && this.date_borrowed.Equals(book.date_borrowed) && this.date_returned.Equals(book.date_returned) && this.description.Equals(book.description) && (NHibernateUtil.IsInitialized(book.genre) && this.genre.Equals(book.genre)) || !NHibernateUtil.IsInitialized(book.genre) && this.has_been_readed == book.has_been_readed && this.id == book.id && (NHibernateUtil.IsInitialized(book.publisher) && this.publisher.Equals(book.publisher)) || !NHibernateUtil.IsInitialized(book.publisher) && this.rating == book.rating ) { return(true); } else { return(false); } }
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 = sessions.OpenSession()) using (ITransaction t = s.BeginTransaction()) { s.Persist(cust); t.Commit(); } using (ISession s = sessions.OpenSession()) using (ITransaction t = s.BeginTransaction()) { try { 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(); } catch { throw; } } using (ISession s = sessions.OpenSession()) using (ITransaction t = s.BeginTransaction()) { try { 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(); } catch { throw; } } }
public async Task UnionSubclassAsync() { 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'; await(s.SaveAsync(yomomma)); await(s.SaveAsync(mark)); await(s.SaveAsync(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, (await(s.CreateQuery("from Person").ListAsync())).Count); Assert.AreEqual(1, (await(s.CreateQuery("from Person p where p.class = Customer").ListAsync())).Count); Assert.AreEqual(1, (await(s.CreateQuery("from Person p where p.class = Person").ListAsync())).Count); s.Clear(); IList <Customer> customers = await(s.CreateQuery("from Customer c left join fetch c.salesperson").ListAsync <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 = await(s.CreateQuery("from Customer").ListAsync <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 = await(s.GetAsync <Employee>(mark.Id)); joe = await(s.GetAsync <Customer>(joe.Id)); mark.Address.zip = "30306"; Assert.AreEqual(1, (await(s.CreateQuery("from Person p where p.address.zip = '30306'").ListAsync())).Count); await(s.DeleteAsync(mark)); await(s.DeleteAsync(joe)); await(s.DeleteAsync(yomomma)); Assert.AreEqual(0, (await(s.CreateQuery("from Person").ListAsync())).Count); await(t.CommitAsync()); s.Close(); } }
public async Task SubselectFetchCriteriaAsync() { 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.CreateCriteria(typeof(Parent)) .Add(Expression.Between("Name", "bar", "foo")) .AddOrder(Order.Desc("Name")) .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(); }
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 TestSessionFactory() { //AuditEventListener lis = (AuditEventListener)applicationContext.GetObject("enversEventListener"); Address adr = new Address { number = "16", street = "Diligentei" }; addressRepository.Add(adr); ContBancar cnt = new ContBancar { NumeBanca = "BCR", IBAN = "RO212BCRO423455634", Adresa = adr }; contRepository.Add(cnt); Person persoana = new Person { firstName = "Mihai", lastName = "Popa", cont = cnt }; personRepository.Add(persoana); persoana.lastName = "Popatatu"; personRepository.Update(persoana); IList personRevisionIds; //personRevisionIds = personRepository.GetAllRevisionIds(persoana); //foreach (object personRevId in personRevisionIds) //{ // Person auditedPerson = personRepository.GetRevision(typeof(Person), persoana.id, (long)(int)personRevId); // Assert.IsTrue(auditedPerson.cont is SessionImpl); // System.Console.Write(personRevId + ":" + auditedPerson.firstName + " " + auditedPerson.lastName + " -> " + auditedPerson.address.street); //} Address address = new Address { number = "22", street = "Valea Calugareasca" }; addressRepository.Add(address); Assert.IsTrue(address.id != 0); long id1 = address.id; address.number = "29"; addressRepository.Update(address); Person pers = new Person { firstName = "Ion", lastName = "Gheorghe", address = address }; personRepository.Add(pers); Assert.IsTrue(pers.id != 0); pers.firstName = "Ionel"; personRepository.Update(pers); personRevisionIds = personRepository.GetAllRevisionIds(pers); foreach (object personRevId in personRevisionIds) { Person auditedPerson = personRepository.GetRevision(typeof(Person), pers.id, (long)(int)personRevId); if (auditedPerson.address is INHibernateProxy) { Type tt = ((INHibernateProxy)auditedPerson.address).HibernateLazyInitializer.PersistentClass; object gigi = ((INHibernateProxy)auditedPerson.address).HibernateLazyInitializer.GetImplementation(); } Type t = NHibernateUtil.GetClass(auditedPerson.address); System.Console.Write(personRevId + ":" + auditedPerson.firstName + " " + auditedPerson.lastName + " -> " + auditedPerson.address.street); } address.number = "23"; addressRepository.Update(address); address.number = "24"; addressRepository.Update(address); address = new Address { number = "45", street = "Strada Strada" }; addressRepository.Add(address); ContBancar cont = new ContBancar { NumeBanca = "BRD", IBAN = "RO212423455634", Adresa = address }; contRepository.Add(cont); pers.cont = cont; personRepository.Update(pers); address = new Address { number = "55bis", street = "Alta strada" }; addressRepository.Add(address); ContBancar cont2 = new ContBancar { NumeBanca = "BCR", IBAN = "RO33BCRO212423455634", Adresa = address }; contRepository.Add(cont2); pers.cont = cont2; personRepository.Update(pers); cont.IBAN += "P2"; contRepository.Update(cont); Person pers2 = new Person { firstName = "Mihai", lastName = "Trompetzescu", address = address, cont = cont }; personRepository.Add(pers2); address = addressRepository.GetById(id1); Assert.IsTrue(address.number == "24" && address.street == "Valea Calugareasca"); address = new Address { number = "123", street = "P-asta o stergem" }; addressRepository.Add(address); addressRepository.Remove(address); }
public ConstantProjection(object value) : this(value, NHibernateUtil.GuessType(value.GetType())) { }
public void GuessType() { Assert.That(NHibernateUtil.GuessType(_replacedType), Is.EqualTo(_testDefaultType)); }
public async Task TestLazyDynamicClassAsync(SingleCarQueryDelegate singleCarQueryHandler, AllModelQueryDelegate allModelQueryHandler, CancellationToken cancellationToken = default(CancellationToken)) { ITransaction t; IDictionary cars; IList models; using (ISession s = OpenSession()) { t = s.BeginTransaction(); cars = new Hashtable(); cars["Description"] = "Cars"; IDictionary monaro = new Hashtable(); monaro["ProductLine"] = cars; monaro["Name"] = "Monaro"; monaro["Description"] = "Holden Monaro"; IDictionary hsv = new Hashtable(); hsv["ProductLine"] = cars; hsv["Name"] = "hsv"; hsv["Description"] = "Holden hsv"; models = new List <IDictionary> { monaro, hsv }; cars["Models"] = models; await(s.SaveAsync("ProductLine", cars, cancellationToken)); await(t.CommitAsync(cancellationToken)); } using (ISession s = OpenSession()) { t = s.BeginTransaction(); cars = singleCarQueryHandler(s); models = (IList)cars["Models"]; Assert.IsFalse(NHibernateUtil.IsInitialized(models)); Assert.AreEqual(2, models.Count); Assert.IsTrue(NHibernateUtil.IsInitialized(models)); s.Clear(); IList list = allModelQueryHandler(s); foreach (IDictionary ht in list) { Assert.IsFalse(NHibernateUtil.IsInitialized(ht["ProductLine"])); } var model = (IDictionary)list[0]; Assert.IsTrue(((IList)((IDictionary)model["ProductLine"])["Models"]).Contains(model)); s.Clear(); await(t.CommitAsync(cancellationToken)); } using (ISession s = OpenSession()) { t = s.BeginTransaction(); cars = singleCarQueryHandler(s); await(s.DeleteAsync(cars, cancellationToken)); await(t.CommitAsync(cancellationToken)); } }
private static Predicate <object> CreateShouldSerializeForLazyProperty(string propertyName) { return(entity => NHibernateUtil.IsPropertyInitialized(entity, propertyName)); }
public RezultatiUkupnoForm(int takmicenjeId, DeoTakmicenjaKod deoTakKod, int startRezTakmicenjeId, bool forViewingOnly) { InitializeComponent(); this.deoTakKod = deoTakKod; this.forViewingOnly = forViewingOnly; Cursor.Current = Cursors.WaitCursor; Cursor.Show(); ISession session = null; try { using (session = NHibernateHelper.Instance.OpenSession()) using (session.BeginTransaction()) { CurrentSessionContext.Bind(session); takmicenje = DAOFactoryFactory.DAOFactory.GetTakmicenjeDAO().FindById(takmicenjeId); NHibernateUtil.Initialize(takmicenje); IList <RezultatskoTakmicenje> svaRezTakmicenja = loadRezTakmicenja(takmicenjeId); if (svaRezTakmicenja.Count == 0) { throw new BusinessException(Strings.NO_KATEGORIJE_I_TAKMICENJA_ERROR_MSG); } rezTakmicenja = takmicenje.getRezTakmicenjaViseboj(svaRezTakmicenja, deoTakKod, false); if (rezTakmicenja.Count == 0) { throw new BusinessException("Ne postoji takmicenje II ni za jednu kategoriju."); } RezultatskoTakmicenje startRezTakmicenje = null; if (startRezTakmicenjeId != -1) { startRezTakmicenje = findRezTakmicenje(startRezTakmicenjeId, rezTakmicenja); if (startRezTakmicenje == null) { throw new BusinessException("Ne postoje rezultati viseboj za dato takmicenje."); } } initUI(startRezTakmicenje); } } catch (BusinessException) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw; } catch (InfrastructureException) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw; } catch (Exception ex) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw new InfrastructureException(ex.Message, ex); } finally { Cursor.Hide(); Cursor.Current = Cursors.Arrow; CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory); } }
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(); } }
public void MultipleCollectionFetch() { 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; s.Persist(p); Product p2 = new Product(); p2.ProductId = "X525"; p2.Description = "nose stud"; p2.Price = 3.0m; p2.NumberAvailable = 105; s.Persist(p2); Customer c = new Customer(); c.Address = "St Kilda Rd, MEL, 3000"; c.Name = "Virginia"; c.CustomerId = "C111"; s.Persist(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; t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); c = (Customer) s.CreateQuery( "from Customer c left join fetch c.Orders o left join fetch o.LineItems li left join fetch li.Product p"). UniqueResult(); 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); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); s.Delete("from LineItem"); s.Delete("from Order"); s.Delete("from Customer"); s.Delete("from Product"); t.Commit(); s.Close(); }
public IQuery SetEntity(int position, object val) { SetParameter(position, val, NHibernateUtil.Entity(NHibernateProxyHelper.GuessClass(val))); return(this); }
public void TestSequentialSelects() { using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { Employee mark = new Employee(); mark.Name = "Mark"; mark.Title = "internal sales"; mark.Sex = 'M'; mark.Address = "buckhead"; mark.Zip = "30305"; mark.Country = "USA"; Customer joe = new Customer(); joe.Name = "Joe"; joe.Address = "San Francisco"; joe.Zip = "54353"; joe.Country = "USA"; joe.Comments = "very demanding"; joe.Sex = 'M'; joe.Salesperson = mark; Person yomomma = new Person(); yomomma.Name = "mom"; yomomma.Sex = 'F'; s.Save(yomomma); s.Save(mark); s.Save(joe); s.Flush(); s.Clear(); Person p = s.Get <Person>(yomomma.Id); Assert.AreEqual(yomomma.Name, p.Name); Assert.AreEqual(yomomma.Sex, p.Sex); s.Clear(); // Copied from H3. Don't really know what it is testing //Assert.AreEqual(0, s.CreateQuery("from System.Serializable").List().Count); Assert.AreEqual(3, s.CreateQuery("from Person").List().Count); Assert.AreEqual(1, s.CreateQuery("from Person p where p.class is null").List().Count); Assert.AreEqual(1, s.CreateQuery("from Person p where p.class = Customer").List().Count); Assert.AreEqual(1, s.CreateQuery("from Customer c").List().Count); s.Clear(); IList customers = s.CreateQuery("from Customer c left join fetch c.Salesperson").List(); foreach (Customer c in customers) { Assert.IsTrue(NHibernateUtil.IsInitialized(c.Salesperson)); Assert.AreEqual("Mark", c.Salesperson.Name); } Assert.AreEqual(1, customers.Count); s.Clear(); mark = (Employee)s.Get(typeof(Employee), mark.Id); joe = (Customer)s.Get(typeof(Customer), joe.Id); mark.Zip = "30306"; s.Flush(); s.Clear(); Assert.AreEqual(1, s.CreateQuery("from Person p where p.Zip = '30306'").List().Count); tx.Commit(); } }