1
[Test]
public void Artist_gets_stored_properly()
{
    using (ISession session = NHHelper.GetSession())
    {
        Artist artist = new Artist() { Name = "Somathilaka Jayamaha" };

        artist.Songs = new List<Song>()
        {
            new Song(){Artist = artist, Name = "Manamaala girawu"},
            new Song(){Artist = artist, Name = "Sende andura"},
            new Song(){Artist = artist, Name = "Sunilwan nuwan"}
        };

        foreach (var s in artist.Songs)
        {
            session.Save(s);
        }
        session.Save(artist);
    }

    using (ISession session = NHHelper.GetSession())
    {
        Artist artist = session.Query<Artist>().Single(x => x.Name == "Somathilaka Jayamaha");
        Assert.AreEqual(3, artist.Songs.Count);
        Assert.AreEqual("Sende andura", artist.Songs[1].Name);
    }
}

public class Artist
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual IList<Song> Songs { get; set; }
    }

    public class Song
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string WebPath { get; set; }
        public virtual string FilePath { get; set; }
        public virtual bool Downloaded { get; set; }
        public virtual Artist Artist { get; set; }

        void Download(IDownloader downloader)
        {
        }
    }

I have the above test case and it fails at this line : Assert.AreEqual(3, artist.Songs.Count);. The songs do not get saved it seems. I use automapping and have Cascade.All() for the collection fields in mapping overrides and have lazyloading off. I can't understand why this test fails. As you can see, I manually saved the 3 songs as well though as I understand it, I don't need to do that when I have Cascade.All() for Artist.Songs field. Can someone tell me what I am doing wrong? Thanks.

MS SQLServer 2005, .NET 3.5, FluentNHibernate 1.2.0.712

nakiya
  • 14,063
  • 21
  • 79
  • 118

1 Answers1

3

You are not using a transaction, and you are never flushing your session.

The only reason you are getting the inserts is because you are using an identity generator, which inserts when you call Save (this is a limitation, not a feature).

The correct way to to this:

using (ISession session = NHHelper.GetSession())
using (var transaction = session.BeginTransaction())
{
    Artist artist = new Artist { Name = "Somathilaka Jayamaha" };

    artist.Songs = new List<Song>()
    {
        new Song{Artist = artist, Name = "Manamaala girawu"},
        new Song{Artist = artist, Name = "Sende andura"},
        new Song{Artist = artist, Name = "Sunilwan nuwan"}
    };

    session.Save(artist);
    transaction.Commit();
}
Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154