最近開始接觸Castle ActiveRecord,學習資料大部分是從網上找到的.這裡要特別感謝TerryLee的系列文章:Castle 開發系列 ,在Castle的學習之路上,這個系列文章對我的影響是十分巨大的!除了這個系列文章之外,Castle的官方網站也是學習Castle的好去處!
本篇學習筆記從一個簡單對象的CURD操作入手,介紹ActiveRecord!
主要內容:
1.ActiveRecord概述
2.准備數據表
3.編寫實體類
4.編寫配置文件
5.對象的CRUD操作
6.表示層調用
一、ActiveRecrod概述
ActiveRecord是Castle中提供的一個數據訪問框架,它在底層封裝了NHibernate的操作.與NHibernate相比,ActiveRecord使用特性來代替映射文件hbm.xml,它提供的簡潔的O/R映射會讓你驚歎原來實現持久化數據層是那麼簡單.
二、准備數據表
Create Table [Users] ( [ID] Int Identity(1,1) Primary Key, [LoginName] Varchar(50) not null, [Password] Varchar(20) not null )
三、編寫實體類User
1.引用Castle.ActiveRecord.dll組件;
2.引用Castle.ActiveRecord名稱空間:
using Castle.ActiveRecord;
3.讓User類繼承ActiveRecordBase類(此類處於Castle.ActiveRecord名稱空間之下):
public class User : ActiveRecord { // }
4.用[ActiveRecrod()]為類添加特性,指出User類對應的數據表是Users:
[ActiveRecord("Users")] public class User : ActiveRecordBase { // }
5.用[Property()]為屬性添加特性,指出屬性對應數據表中的列:
[ActiveRecord("Users")] public class User : ActiveRecordBase { private int _id; private string _name; private string _password; //[PrimaryKey]特性指定Id作為主鍵 //用PrimaryKeyType.Identity來說明了主鍵的類型為自增型的 [PrimaryKey(PrimaryKeyType.Identity, "ID")] public int Id { get { return _id; } set { _id = value; } } [Property("LoginName")] public string Name { get { return _name; } set { _name = value; } } //若屬性名與列名一致可省略不寫 [Property] public string Password { get { return _password; } set { _password = value; } } }
四、編寫配置文件App.config或web.config.由於ActiveRecord在底層封裝了NHibernate,故配置文件的信息和NHibernate一致.
App.config:
<?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="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" /> <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" /> <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" /> <add key="hibernate.connection.connection_string" value="UID=sa;Password=123456789;Initial Catalog=Castle;Data Source=EMMALEE" /> </config> </activerecord> </configuration> web.config <?xml version="1.0"?> <configuration> <configSections> <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/> </configSections> <activerecord isWeb="true"> <config> <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" /> <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" /> <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" /> <add key="hibernate.connection.connection_string" value="UID=sa;Password=123456789;Initial Catalog=Castle;Data Source=EMMALEE" /> </config> </activerecord> <system.web> <compilation debug="true"/> <authentication mode="Windows"/> <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors> </system.web> </configuration>
五、對象的CRUD操作.類ActiveRecordBas中定義了許多靜態方法用於對象的CRUD操作,如:Create、Delete、DeleteAll、FindAll、FindAllByProperty、FindByPrimaryKey、Save等等一些靜態方法.
1.Create操作
User objUser = new User(); objUser.Name = "jailu"; objUser.Password = "123456789"; objUser.Create();
2.Read操作
User objUser = User.Find(1); //檢索主鍵ID為1的User對象 string strName = objUser.Name; string strPassword = objUser.Password;
3.Update操作
User objUser = User.Find(1); //檢索主鍵ID為1的User對象 objUser.Name = "EmmaLee"; objUser.Password = "987654321"; objUser.Update();
4.Delete操作
User objUser = User.Find(1); //檢索主鍵ID為1的User對象 objUser.Delete();
5.完整的User類代碼:
using System; using System.Collections.Generic; using System.Text; using System.Collections; using Castle.ActiveRecord; using Castle.ActiveRecord.Queries; namespace CastleTest { //為User類添加特性,其實就是告訴ActiveRecord,User類所對應的數據庫中的數據表名為Users [ActiveRecord("Users")] public class User : ActiveRecordBase { private int _id; private string _name; private string _password; //[PrimaryKey]特性指定Id作為主鍵 //用PrimaryKeyType.Identity來說明了主鍵的類型為自增型的 [PrimaryKey(PrimaryKeyType.Identity, "ID")] public int Id { get { return _id; } set { _id = value; } } [Property("LoginName")] public string Name { get { return _name; } set { _name = value; } } //若屬性名與列名一致可省略不寫 [Property] public string Password { get { return _password; } set { _password = value; } } public static void DeleteAll() { DeleteAll(typeof(User)); } public static IList FindAll() { return (IList)FindAll(typeof(User)); } public static User Find(int id) { return (User)FindByPrimaryKey(typeof(User), id); } /**//// <summary> /// 根據LogonName查詢User對象,在測試HQL查詢時用到 /// </summary> /// <param name="LogonName">登錄名</param> /// <returns>User對象數組</returns> public static User[] GetUsersByLogonName(string LogonName) { SimpleQuery query = new SimpleQuery(typeof(User),@"from User user where user.Name = ?",LogonName); return (User[])ExecuteQuery(query); } } }
六、表示層調用:
private void button1_Click(object sender, EventArgs e) { //初始化,獲取連接字符串等信息 IConfigurationSource source = System.Configuration.ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource; ActiveRecordStarter.Initialize(source, typeof(User)); User objUser = new User(); objUser.Name = "jailu"; objUser.Password = "123456789"; objUser.Create(); }
至此,ActiveRecord的初步接觸就算是完成了.