Castle ActiveRecord学习实践(10) 深度分析Schema Pitfals2011-02-03 cnblogs terrylee摘要:写这篇文章缘于昨天跟Linkin的一段聊天。我在使用ActiveRecord的一些技巧一文中的由实体类生成数据库表提到了这样一句话:生成数据库表时只有当该表不存在时ActiveRecord才会生成,否则表如果存在ActiveRecord不会做任何事情,也不会报任何错误。Linkin说他在实验时如果数据库表存在,ActiveRecord会删除表中的记录,其实这句话是在有些情况下是不对的,本篇文章将详细介绍Castle ActiveRecord中的Schema Pitfals。主要内容1.引言2.CreateSchema和DropSchema3.CreateSchemaFromFile4.GenerateCreationScripts和GenerateDropScripts一.引言我在Castle ActiveRecord学习实践(9):使用ActiveRecord的一些技巧一文中的由实体类生成数据库表提到了这样一句话:生成数据库表时只有当该表不存在时ActiveRecord才会生成,否则表如果存在ActiveRecord不会做任何事情,也不会报任何错误。Linkin说他在实验时如果数据库表存在,ActiveRecord会删除表中的记录,其实那句话是在有些情况下是不对的,通过后面的分析我们会看到。Castle ActiveRecord为我们提供了由实体类生成数据库表的方法,它其实在底层是封装了NHibernate.Tool.hbm2ddl中的SchemaExport,既创建数据库表的方法都是通过SchemaExport类来完成了,所有的这些方法都在ActiveRecordStarter中提供,列表如下:
方 法 | 示例 |
CreateSchema() | ActiveRecordStarter.CreateSchema(); |
CreateSchemaFromFile() | ActiveRecordStarter.CreateSchemaFromFile("blog.sql"); |
DropSchema () | ActiveRecordStarter.DropSchema(); |
GenerateDropScripts() | ActiveRecordStarter.GenerateDropScripts("blog.sql"); |
GenerateCreationScripts() | ActiveRecordStarter.GenerateCreationScripts("blog.sql"); |
二.CreateSchema和DropSchemaCreateSchema根据实体类来生成数据库表,在调用ActiveRecordStarter.CreateSchema()之后,我们来看一下ActiveRecord中执行了什么操作:
public static void CreateSchema()
{
CheckInitialized();
foreach(Configuration config in ActiveRecordBase._holder.GetAllConfigurations())
{
SchemaExport export = CreateSchemaExport(config);
try
{
export.Create( false, true );
}
catch(Exception ex)
{
throw new ActiveRecordException( "Could not create the schema", ex );
}
}
}