[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)
{
}
}
我有上述测试用例,但在此行失败:Assert.AreEqual(3, artist.Songs.Count);
。这些歌似乎没有得到保存。我使用自动化并在映射覆盖的集合字段中使用Cascade.All()
并关闭延迟。我无法理解为什么这个测试失败了。正如您所看到的,我手动保存了3首歌曲,但据我所知,当Cascade.All()
Artist.Songs
字段为{{1}}时,我不需要这样做。有人能告诉我我做错了什么吗?谢谢。
MS SQLServer 2005,.NET 3.5,FluentNHibernate 1.2.0.712
答案 0 :(得分:3)
您没有使用交易,而且您永远不会刷新您的会话。
获取插入的唯一原因是因为您使用的是identity
生成器,当您调用Save
时会插入该生成器(这是一个限制,而不是一个功能) )。
正确的方法:
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();
}