NHibernate show_sql 未显示所有插入

NHibernate show_sql not showing all inserts

show_sql 在控制台中显示 SQL 交互的输出,但特定实体类型 TimeOff 除外。插入内容未显示在控制台中。

这显示了输出:

var employee = new Employee();
_session.Save(employee);

这不是:

var timeOff = new TimeOff
{
  Employee = new Employee{Id=1}
};
_session.Save(timeOff);

插入仍在进行。

这是我的 fluent-nhibernate 配置和 NUnit 启动和拆卸:

[TestFixture]
public class InsertTests : IDisposable
{
    public InsertTests()
    {
       var cs = ConfigurationManager.ConnectionStrings[0].ConnectionString;

       var config = MsSqlConfiguration.MsSql2008
            .ConnectionString(cs)
            .ShowSql()
            .FormatSql();

       var sessionFactory = Fluently.Configure()
        .Database(config)
        .Mappings(m =>
            m.FluentMappings.AddFromAssemblyOf<EmployeeMap>())
        .BuildSessionFactory();

       _session = sessionFactory.OpenSession();
    }

    private readonly ISession _session;
    private ITransaction _transaction;

    [SetUp]
    public virtual void SetUp()
    {
      _transaction = _session.BeginTransaction();
    }

    [Test]
    public void no_sql_output()
    {
      var timeOff = new TimeOff
      {
          Employee = new Employee{Id=1}
      };
      _session.Save(timeOff);
    }

    [Test]
    public void shows_sql_output()
    {
       var employee = new Employee();
     
       _session.Save(employee);
    }

    [TearDown]
    public virtual void TearDown()
    {
      //_transaction.Rollback();
      _transaction.Commit();
    }    
}

这是我的相关地图:

public class TimeOffMap : ClassMap<TimeOff>
{
    public TimeOffMap()
    {
        Table("timeoff");

        Id(x => x.Id).Column("timeoff_Id").GeneratedBy.Guid();

        References(x => x.Employee);
     }
 }
 
 
public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        Table("employees");

        Id(x => x.Id).Column("employee_id").GeneratedBy.Native();

        HasMany(x => x.TimeOff)
            .Cascade.All()
            .Inverse()
            .KeyColumn("employee_id");
     }
 }

两个映射之间的唯一区别是 TimeOff 有一个 Guid Id 而 Employee 有一个 Int。如果我在同一个事务中插入一个 Employee 和 TimeOff,只有 Employee Insert 显示。

这里的区别在于 TimeOff 实体实际数据库保存被推迟并且仅在事务提交时发生(在您的情况下是测试拆卸 TearDown 方法)或显式 _session.Flush称呼 。所以我相信这就是为什么您在测试用例方法 can_add_timeoff 输出中看不到它的原因。