ActiveRecord是Castle项目基于NHibernate开发的一套O/R Mapping框架。与NHibernate的重要区别在于ActiveRecord无须HBM映射文件,使用Attribute来描述对象到数据库的映射关系,且ActiveRecord使用了Martin Fowler在《Patterns of Enterprise Application Architecture》中提到的Active Record模式来作为中心设计思想。
下面我们看看ActiveRecord的一个例子:
[ActiveRecord] public class User : ActiveRecordBase<User> { private int id; private string username; private string password; public User() { } public User(string username, string password) { this.username = username; this.password = password; } [PrimaryKey] public int Id { get { return id; } set { id = value; } } [Property] public string Username { get { return username; } set { username = value; } } [Property] public string Password { get { return password; } set { password = value; } } }
在定义对象的结构后,就可以直接使用了:
初始化ActiveRecord:
XmlConfigurationSource source = new XmlConfigurationSource("appconfig.xml"); ActiveRecordStarter.Initialize( source, typeof(User) );
通过ActiveRecord自动在数据库中创建对应表:
ActiveRecordStarter.CreateSchema();
创建一个用户:
User user = new User("admin", "123"); user.Create();
[Serializable] public class Person { private int id; private string firstName; private string lastName; private DateTime? birthDate; private double? weightInKilograms; private double? heightInMeters; public Person() { } public int Id { get { return id; } set { id = value; } } public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } public DateTime? BirthDate { get { return birthDate; } set { birthDate = value; } } public double? WeightInKilograms { get { return weightInKilograms; } set { weightInKilograms = value; } } public double? HeightInMeters { get { return heightInMeters; } set { heightInMeters = value; } } }