单元测试流畅的nhibernate存储库与内存中的sql lite -没有这样的表错误

本文关键字:lite 错误 sql nhibernate 存储 内存 单元测试 | 更新日期: 2023-09-27 18:13:39

我正在尝试使用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' [Type: String (0)], @p1 = 3 [Type: 0)]Double (0)], @p2 = True [Type: Boolean (0)], @p3 = True [Type: Boolean](0)], @p4 = NULL [Type: String (0)]

NHibernate.Exceptions。GenericADOException不能插入:[MoneyManagerCore。[SQL: INSERT INTO Expense]isnecessary, isperiodic, comment), ?, ?, ?);选择last_insert_rowid ())NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert (SqlCommandInfoinsertSQL, ISessionImplementor session, IBinder binderNHibernate.Persister.Entity.AbstractEntityPersister.Insert(对象[]字段,Boolean[] notNull, SqlCommandInfo sql,对象obj,ISessionImplementor session) NHibernate.Persister.Entity.AbstractEntityPersister.Insert(对象[]字段,对象obj, ISessionImplementor session)NHibernate.Action.EntityIdentityInsertAction.Execute ()NHibernate.Engine.ActionQueue。Execute(IExecutable可执行NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(对象entity, EntityKey key, IEntityPersister persister, BooleanuseIdentityColumn, Object anything, IEventSource,布尔值requiresImmediateIdAccess)NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(对象entity,对象id, IEntityPersisteruseIdentityColumn, Object anything, IEventSource,布尔值requiresImmediateIdAccess)NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(对象实体,字符串entityName,对象任何东西,IEventSource源,布尔值requiresImmediateIdAccessNHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId (SaveOrUpdateEvent事件)NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient (SaveOrUpdateEvent事件)NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.PerformSaveOrUpdate (SaveOrUpdateEvent事件)NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate (SaveOrUpdateEvent事件)NHibernate.Impl.SessionImpl。FireSaveOrUpdate (SaveOrUpdateEvent事件)NHibernate.Impl.SessionImpl。SaveOrUpdate(Object obj) MoneyManagerRepository.NhibernateRepository"1。SaveOrUpdate (T实体)dans nhibernatereitory .cs:第56行UnitTests.RespositoryTest.InsertAndLoadExpense()在cs:第28行System.Data.SQLite.SQLiteException SQL逻辑错误或缺少数据库没有这样的表:费用

有谁能帮我解决这个问题吗?

单元测试流畅的nhibernate存储库与内存中的sql lite -没有这样的表错误

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

在内存中使用sqlite连接必须始终是相同的,因为内存中的数据库与连接一起生存和死亡。

我:

  1. 使public ISessionFactory Session { get; set; }私有,并将其重命名为sessionfactory,因为会话是误导
  2. 有一个方法public ISession OpenSession()和在sqlliteddatabase实现它return _sessionfactory.OpenSession(_connection);,其中连接是相同的连接在SchemaExport().Execute