你没记错,毛里西奥。以下代码显示了如何创建或更新架构。当 Validate() 引发异常时,更新将运行。当某个字段在数据库中可用但在配置中不可用时,不会抛出异常。拥有额外的字段是完全合法的:你不希望它们被删除,我希望?这可能会造成巨大的伤害...
下面的代码显示了测试、创建、验证和更新,每个步骤都有正确的异常处理。代码已简化,但它应该让您了解如何进行验证。
此代码有助于以实体为中心 (POCO) ORM 配置,您可以在其中向您的类添加一个字段,它将在数据库中自动更新。不是以表格为中心,字段领先。
// executes schema script against database
private static void CreateOrUpdateSchema(Configuration config)
{
// replace this with your test for existence of schema
// (i.e., with SQLite, you can just test for the DB file)
if (!File.Exists(DB_FILE_NAME))
{
try
{
SchemaExport export = new SchemaExport(config);
export.Create(false, true);
}
catch (HibernateException e)
{
// create was not successful
// you problably want to break out your application here
MessageBox.Show(
String.Format("Problem while creating database: {0}", e),
"Problem");
}
}
else
{
// already something: validate
SchemaValidator validator = new SchemaValidator(config);
try
{
validator.Validate();
}
catch (HibernateException)
{
// not valid, try to update
try
{
SchemaUpdate update = new SchemaUpdate(config);
update.Execute(false, true);
}
catch (HibernateException e)
{
// update was not successful
// you problably want to break out your application here
MessageBox.Show(
String.Format("Problem while updating database: {0}", e),
"Problem");
}
}
}
}
-- 亚伯 --