Castle.ActiveRecord (V3.0.0.130)

Old發表於2013-06-21

為專案新增 Castle.ActiveRecord 的引用:

安裝成功後,檢視專案的引用如圖:

配置檔案 App.Config (MySQL)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
  </configSections>
  <activerecord>
    <config>
      <add key="connection.driver_class" value="NHibernate.Driver.MySqlDataDriver" />
      <add key="dialect" value="NHibernate.Dialect.MySQL5Dialect" />
      <add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
      <add key="connection.connection_string" value="Server=localhost;Port=3306;Database=testDb;Uid=root;Pwd=mysql;Charset=utf8;" />
      <add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
    </config>
  </activerecord>
</configuration>

初始化 (新增 System.Configuration.dll 的引用)

Castle.ActiveRecord.Framework.IConfigurationSource source = System.Configuration.ConfigurationManager.GetSection("activerecord") as IConfigurationSource;
Castle.ActiveRecord.ActiveRecordStarter.Initialize(source, new Type[] { typeof(User) });

實體類

    [ActiveRecord("user")]
    class User: ActiveRecordBase<User> //ActiveRecordValidationBase<User>
    {
        [PrimaryKey(PrimaryKeyType.Identity, Column = "ID")]
        public int ID { get; set; }
        [Property(Column = "Name")]
        public string Name { get; set; }
    }

UI 上的使用:

dataGridView1.DataSource = User.FindAll();