开发者

What's the proper way to save a object with nhibernate?

开发者 https://www.devze.com 2022-12-13 01:36 出处:网络
I\'m new to Hibernate, I just started to do a mapping to a table, but I\'m having some problems when I try to write an object, here\'s my unit test:

I'm new to Hibernate, I just started to do a mapping to a table, but I'm having some problems when I try to write an object, here's my unit test:

[TestFixture]
public class FacilityRepositoryTest : DatabaseRepositoryTestsBase
{
    private IRepository<Facility> repos开发者_开发问答itory = 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);
        }
    }
}

When I run CanCreateOneFacility, I get this exception:

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()

I started debugging the test and no exception is thrown AND the data IS being recorded, but after the test is finished comes the exception.

What am I doing wrong? is this an incorrect way to save the objects?


You are using S#arp Architecture, right? I believe DatabaseRepositoryTestsBase already provides a transaction for you, so you don't have to set one up in your test code. So try removing:

repository.DbContext.BeginTransaction();

and

repository.DbContext.CommitTransaction();

and see if that works.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号