我对Sqlite和Nhibernate有很大的疑问。我编写了一个小型控制台应用程序来测试内存数据库的不同设置。我可以使用Raw SQL提交插入数据,甚至可以使用NHibernate在会话内部添加数据。我也可以通过打开SQLiteConnection和原始SQL来检索数据,但是当我尝试通过Session.get()
获取对象时,它总是返回null。
这是我的配置:
Configuration cfg = new Configuration();
string connectionString = @"FullUri=file:memorydb.db?mode=memory&cache=shared";
IDictionary<string, string> props = new Dictionary<string,string>();
props.Add("connection.provider","NHibernate.Connection.DriverConnectionProvider");
props.Add("connection.connection_string", connectionString);
props.Add("connection.driver_class","NHibernate.Driver.SQLite20Driver");
props.Add("dialect", "NHibernate.Dialect.SQLiteDialect");
props.Add("connection.release_mode", "on_close");
props.Add("ProxyFactoryFactoryClass","NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle");
props.Add("show_sql", "true");
cfg.SetProperties(props);
cfg.AddAssembly("ConsoleApp2");
SQLiteConnection conn = new SQLiteConnection(@"FullUri=file:memorydb.db");
conn.Open();
Teacher teacher = new Teacher();
teacher.Id = 1223;
teacher.Name = "Test";
ISessionFactory factory = cfg.BuildSessionFactory();
这是我的XML映射:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="ConsoleApp2"
namespace="ConsoleApp2.Domain"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:nhibernate-mapping-2.2 ../nhibernate-mapping.xsd">
<class name="Teacher" table="Teacher">
<id name="Id" column="Id" type="Int32">
<generator class="hilo" />
</id>
<property name="Name">
<column name="Name" sql-type="nvarchar" not-null="true" />
</property>
</class>
</hibernate-mapping>
我的会话范围: 使用(ISession会话= factory.OpenSession()) { 使用(var tx = session.BeginTransaction()) { SchemaExport导出=新的SchemaExport(cfg); export.Execute(false,true,false,session.Connection,null); tx.Commit(); }
using (var test = session.BeginTransaction())
{
session.Save(teacher);
test.Commit();
}
using (SQLiteConnection connection = new SQLiteConnection(@"FullUri=file:memorydb.db?mode=memory&cache=shared"))
{
connection.Open(); ;
string sql = "PRAGMA table_info('Teacher');";
SQLiteCommand cmd = new SQLiteCommand(sql, connection);
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetName(0));
}
}
using (SQLiteConnection connection = new SQLiteConnection(@"FullUri=file:memorydb.db?mode=memory&cache=shared"))
{
connection.Open(); ;
string sql = "SELECT * From Lehrer";
SQLiteCommand cmd = new SQLiteCommand(sql, connection);
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetValue(1));
}
}
var y = session.Get<ITeacher>(1223);
}
正如我所说,这只是一个测试解决方案。我试图让我的测试用例在单个会话中可运行。我知道那里有很多教程/指南等,但是我发现没有一个可以解决在内存数据库中植入testdata并在同一会话中执行测试的问题。