我有一段代码将元素添加到实体集合(一对多关系)。这是带有ISession.Save的版本
using (ISession session = sessionFactory.OpenSession())
{
var package = session.QueryOver<Package>().Where(x => x.ID == selectedPackage).SingleOrDefault();
foreach(var themeId in selectedThemes)
{
var selectedTheme = session.QueryOver<HBTheme>().Where(x => x.ID == themeId).SingleOrDefault();
if (selectedTheme != null)
{
package.Themes.Add(new PackageTheme() { Package = package, Theme = selectedTheme });
}
}
session.Save(package);
}
那个版本对我不起作用。正如我用ITransaction编写的测试一样,我将其更改为以下内容:
using (ISession session = sessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
var package = session.QueryOver<Package>().Where(x => x.ID == selectedPackage).SingleOrDefault();
foreach(var themeId in selectedThemes)
{
var selectedTheme = session.QueryOver<HBTheme>().Where(x => x.ID == themeId).SingleOrDefault();
if (selectedTheme != null)
{
package.Themes.Add(new PackageTheme() { Package = package, Theme = selectedTheme });
}
}
transaction.Commit();
}
现在它可以工作了。package.Themes集合中的元素存储在数据库中。怎么来的?谢谢!