Creating the DDL script and keep it in sync might be a time consuming tasks. However every developer has their own preferences, and to some extent companies tend to work some specific way or another.
ActiveRecord exposes a NHibernate feature to create and drop schemas. The methods are CreateSchema and DropSchema. You can also use GenerateCreationScripts and GenerateDropScripts if you just want to generate a file with the scripts and at last you can use CreateSchemaFromFile to execute a DDL script. All these methods are exposed by the ActiveRecordStarter class and can only be used after you have invoked one of the Initialize overloads.
Letting ActiveRecord generate the schema
Letting AR generate and execute the creation schema might be good for some scenarios. For example, to prototype an application or on the test cases.
If you want to stick with this approach you're also advised to use more uncommon properties on attributes to guide the schema generation like NotNull, Length and ColumnType:
[ActiveRecord("Blogs")] public class Blog : ActiveRecordBase { private int _id; private String _name; private String _author; [PrimaryKey(PrimaryKeyType.Native, "blog_id")] public int Id { get { return _id; } set { _id = value; } } [Property("blog_name", NotNull=true, Length=25)] public String Name { get { return _name; } set { _name = value; } } [Property("blog_author", NotNull=true, Length=50)] public String Author { get { return _author; } set { _author = value; } } }
Be aware that the schema generation is not bullet proof. For some complex models the generated script might be buggy. For 90% of the cases it's alright though.
The following code will initialize the framework and generate the schema:
ActiveRecordStarter.Initialize(new XmlConfigurationSource("appconfig.xml"), typeof(Blog) ); ActiveRecordStarter.CreateSchema();
but note that the CreateSchema method will only create the tables that did not exist in the database, if the existing table has been changed, the CreateSchema() method will do nothing.
Running an external script file
This is a better alternative, especially if you work on team that has someone dedicated to keep the database schema up to date. So the suggestion is to make the sql files part of the projects and executing them.
ActiveRecordStarter.Initialize(new XmlConfigurationSource("appconfig.xml"), typeof(Blog) ); ActiveRecordStarter.CreateSchemaFromFile("myscript1.sql"); ActiveRecordStarter.CreateSchemaFromFile("myscript2.sql");
