使用nhibernate保存对象的正确方法是什么?

时间:2009-11-26 04:59:13

标签: c# sql-server unit-testing nhibernate

我是Hibernate的新手,我刚刚开始映射到一个表,但是当我尝试编写一个对象时遇到了一些问题,这是我的单元测试:

[TestFixture]
public class FacilityRepositoryTest : DatabaseRepositoryTestsBase
{
    private IRepository<Facility> repository = new Repository<Facility>();

    [Test]
    public void CanGetAllFacilities()
    {
        IList<Facility> allFacilities=repository.GetAll();
        Assert.IsNotNull(allFacilities);
        foreach (Facility facility in allFacilities)
        {
            Console.WriteLine(facility.NAME);
        }
    }
    [Test]
    public void CanCreateOneFacility()
    {
        try
        {
            repository.DbContext.BeginTransaction();
            Facility facility = new Facility();
            facility.FACILITY_CODE = "abc";
            facility.NAME = "Nameds";
            facility.ADDRESS = "Reinhardt strasse";
            repository.SaveOrUpdate(facility);
            repository.DbContext.CommitTransaction();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

当我运行CanCreateOneFacility时,我得到了这个例外:

TestCase 'PJ1.TestUsingDevDb.PJ1Web.Data.FacilityRepositoryTest.CanCreateOneFacility'
failed: TearDown : NHibernate.TransactionException : Transaction not successfully started
--TearDown
en NHibernate.Transaction.AdoTransaction.CheckBegun()
en NHibernate.Transaction.AdoTransaction.Rollback()

我开始调试测试并且没有抛出异常并且正在记录数据,但是在测试完成之后会出现异常。

我做错了什么?这是一种保存对象的错误方法吗?

1 个答案:

答案 0 :(得分:0)

您正在使用S#arp架构,对吗?我相信DatabaseRepositoryTestsBase  已经为您提供了一个交易,因此您不必在测试代码中设置一个。所以尝试删除:

repository.DbContext.BeginTransaction();

repository.DbContext.CommitTransaction();

看看是否有效。