3

我正在尝试使用 Fluent NHibernate 为存储库模式编写单元测试。我选择使用内存中的 sqlite 数据库以避免 sql server 访问(这可以用于集成测试)。

以下是我使用的类:

public enum ExpenseCategory
{
    Eat,
    Clothes,
    Car,
    Leisure,
    Rent,
    House,
    Lecture,
    Trip,
    Restaurent
}

public class Expense
{
    public virtual int Id { get; set; }
    public virtual ExpenseCategory Category { get; set; }
    public virtual double Amount { get; set; }
    public virtual bool IsNecessary { get; set; }
    public virtual bool IsPeriodic { get; set; }
    public virtual string Comment { get; set; }
}

    public ExpenseMapping()
    {
        Table("Expense");
        Id(x => x.Id).Column("idexpense");
        Map(x => x.Category).Column("category");
        Map(x => x.Amount).Column("amount");
        Map(x => x.IsNecessary).Column("isnecessary");
        Map(x => x.IsPeriodic).Column("isperiodic");
        Map(x => x.Comment).Column("comment");
    }
    interface IRepository<T>
{
    T GetById(int id);
    void SaveOrUpdate(T entity);
    void Delete(T entity);
    List<T> GetAll();
}

public interface IDatabase
{
    Configuration Config { get; set; }
    ISessionFactory Session { get; set; }
}

public class NhibernateRepository<T> : IRepository<T>
{
    private readonly Configuration _configuration;
    private readonly ISessionFactory _session;

    public NhibernateRepository(IDatabase database)
    {
        _configuration = database.Config;
        _session = database.Session;

    }

    public T GetById(int id)
    {
        T retrievedObject;
        using (var session = _session.OpenSession())
        {
            using (var transaction = session.BeginTransaction())
            {
                retrievedObject = session.Get<T>(id);
                transaction.Commit();
            }
        }
        return retrievedObject;
    }

    public void SaveOrUpdate(T entity)
    {
        using (var session = _session.OpenSession())
        {
            using (var transaction = session.BeginTransaction())
            {
                session.SaveOrUpdate(entity);
                transaction.Commit();
            }
        }
    }

    public void Delete(T entity)
    {
        using (var session = _session.OpenSession())
        {
            using (var transaction = session.BeginTransaction())
            {
                session.Delete(entity);
                transaction.Commit();
            }
        }
    }

    public List<T> GetAll()
    {
        IList<T> allObjects;
        using (var session = _session.OpenSession())
        {
            using (var transaction = session.BeginTransaction())
            {
                allObjects = session.CreateCriteria(typeof (T)).List<T>();
                transaction.Commit();
            }
        }

        return (List<T>)allObjects;
    }
}


public class DatabaseSqlLite : IDatabase, IDisposable
{
    public Configuration Config { get; set; }
    public ISessionFactory Session { get; set; }

    public DatabaseSqlLite()
    {
        Session = Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
            .Mappings(m => m.FluentMappings
                            .Add(typeof(ExpenseMapping))
                      )
            .ExposeConfiguration(x => Config = x)
            .BuildSessionFactory();

        SchemaExport export = new SchemaExport(Config);
        export.Execute(true, true, false, Session.OpenSession().Connection, null);

    }

    public void Dispose()
    {
        //S.Dispose();
    }
}

public class DatabaseSqlServer : IDatabase
{
    public Configuration Config { get; set; }
    public ISessionFactory Session { get; set; }

    public DatabaseSqlServer()
    {
       Config = Fluently.Configure()
       .Database(MsSqlConfiguration.MsSql2008
                    .ConnectionString(m => m.Server(@".\SqlExpress")
                    .Database("databasename")
                    .TrustedConnection()))
                .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                .BuildConfiguration();

       Session = Config.BuildSessionFactory();
    }
}

从控制台应用程序中使用 DatabaseSqlServer 类给了我正确的结果。尝试使用 DatabaseSqlLite 类进行单元测试会给我错误:

public class RespositoryTest
{
    [Fact]
    public void InsertAndLoadExpense()
    {
        var database = new DatabaseSqlLite();

        var repository = new NhibernateRepository<Expense>(database);

        var expense = new Expense()
            {
                Amount = 3,
                IsNecessary = true,
                IsPeriodic = true,
                Category = ExpenseCategory.Car
            };
        repository.SaveOrUpdate(expense);
        Assert.Equal(1, repository.GetAll().Count);
    }
}

错误:

PRAGMA foreign_keys = OFF

drop table if exists Expense

PRAGMA foreign_keys = ON

create table Expense (
    idexpense  integer primary key autoincrement,
   category TEXT,
   amount DOUBLE,
   isnecessary BOOL,
   isperiodic BOOL,
   comment TEXT
)

NHibernate: INSERT INTO Expense (category, amount, isnecessary, isperiodic, comment) VALUES (@p0, @p1, @p2, @p3, @p4); 选择 last_insert_rowid();@p0 = 'Car' [类型:字符串 (0)],@p1 = 3 [类型:双精度 (0)],@p2 = True [类型:布尔值 (0)],@p3 = True [类型:布尔 (0)],@p4 = NULL [类型:字符串 (0)]

NHibernate.Exceptions.GenericADOException 无法插入:[MoneyManagerCore.Expense][SQL: INSERT INTO Expense (category, amount, isnecessary, isperiodic, comment) VALUES (?, ?, ?, ?, ?); 选择 last_insert_rowid()] à NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder)à NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Boolean[] notNull, SqlCommandInfo sql, Object obj, ISessionImplementor session)à NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Object obj, ISessionImplementor session)à NHibernate.Action.EntityIdentityInsertAction.Execute()à NHibernate.Engine.ActionQueue.Execute(IExecutable executable)à NHibernate.Event.Default.AbstractSaveEventListener。

谁能帮我解决这个问题?

4

1 回答 1

8

发生的情况是您打开一个连接,创建表并丢弃连接,然后打开另一个指向空数据库的连接。

使用 sqlite inmemory 连接必须始终相同,因为 inmemory 数据库随连接而生和死。

我会:

  1. 由于 Session 具有误导性,因此将其设为public ISessionFactory Session { get; set; }私有并将其重命名为 sessionfactory
  2. 有一个方法public ISession OpenSession()并在 SqlLiteDatabase 中实现它return _sessionfactory.OpenSession(_connection);,其中连接与中使用的连接相同SchemaExport().Execute
于 2013-06-06T12:06:50.083 回答