我一直在关注如何在SQLite中使用NHibernate的一些例子,其中大部分都与单元测试数据库CRUD操作有关。所以,到目前为止我用google搜索和跟踪的例子都与此有关。这很好,但问题是,每次运行我的程序时,数据库都会重新创建!我如何修改我的代码,以便如果数据库已经存在,NHibernate不会创建它?是的,我试图检查File.Exists,但它被忽略了;我相信因为NHibernate首先访问该文件。
这是我的映射:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property>
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<property name="query.substitutions">true=1;false=0</property>
<property name="show_sql">false</property>
</session-factory>
</hibernate-configuration>
我的完整代码:
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using NHibernate;
using NHibernate.Cfg;
using PruebaNHLite.Domain;
namespace PruebaNHLite
{
public class Program
{
public static ISession sess;
public static Configuration cfg;
public static SQLiteConnection connection;
private const string CONNECTION_STRING =
@"Data Source=nhlite.db;Pooling=true;FailIfMissing=false;
BinaryGUID=false;New=false;Compress=true;Version=3";
static void Main(string[] args)
{
Init();
BuildSchema();
Insert();
Retrieve();
sess.Close();
sess = null;
}
public static void Init()
{
// Initialize NHibernate
cfg = new Configuration();
cfg.Configure();
IDictionary<string, string> props = new Dictionary<string, string>();
props.Add("connection.connection_string", CONNECTION_STRING);
props.Add("connection.driver_class", "NHibernate.Driver.SQLite20Driver");
props.Add("dialect", "NHibernate.Dialect.SQLiteDialect");
props.Add("proxyfactory.factory_class", "NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu");
props.Add("query.substitutions", "true=1;false=0");
props.Add("show_sql", "false");
cfg.SetProperties(props);
cfg.AddAssembly(typeof(Person).Assembly);
connection = new SQLiteConnection(CONNECTION_STRING);
connection.Open();
// Get ourselves an NHibernate Session
var sessions = cfg.BuildSessionFactory();
sess = sessions.OpenSession();
}
private static void BuildSchema()
{
NHibernate.Tool.hbm2ddl.SchemaExport schemaExport
= new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
schemaExport.Execute(false, true, false, connection, null);
}
public static void Insert()
{
// Create a Person...
var person = new Person
{
Name = "Almudena",
Surname = "Pamplinas",
Age = 5
};
// And save it to the database
sess.Save(person);
sess.Flush();
}
public static void Retrieve()
{
IQuery q = sess.CreateQuery("FROM Person");
foreach (var p in q.List().Cast<Person>())
{
Console.WriteLine(string.Format("{0} {1}, de {2} años.",
p.Name, p.Surname, p.Age));
}
Console.ReadLine();
}
}
}
答案 0 :(得分:7)
尝试使用SchemaUpdate
代替SchemaExport
。 SchmaExport将删除所有表,约束等,并重新创建它们。 SchemaUpdate将使您的数据库更新。但是,我提醒在生产环境中使用SchemaUpdate / SchemaExport,因为这些不是生产质量的迁移工具。