Active Record学习笔记(一):初步接触
最近开始接触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]
Create Table [Users] (
( [ID] Int Identity(1,1) Primary Key,
    [ID] Int Identity(1,1) Primary Key, [LoginName] Varchar(50) not null,
    [LoginName] Varchar(50) not null, [Password] Varchar(20) not null
    [Password] Varchar(20) not null )
)三、编写实体类User
1.引用Castle.ActiveRecord.dll组件;
2.引用Castle.ActiveRecord名称空间:
 using Castle.ActiveRecord;
using Castle.ActiveRecord;3.让User类继承ActiveRecordBase类(此类处于Castle.ActiveRecord名称空间之下):
 public class User : ActiveRecord
public class User : ActiveRecord {
{ //
   //
 }
}4.用[ActiveRecrod()]为类添加特性,指出User类对应的数据表是Users:
 [ActiveRecord("Users")]
[ActiveRecord("Users")] public class User : ActiveRecordBase
public class User : ActiveRecordBase {
{ //
   //
 }
}5.用[Property()]为属性添加特性,指出属性对应数据表中的列:
 [ActiveRecord("Users")]
[ActiveRecord("Users")] public class User : ActiveRecordBase
public class User : ActiveRecordBase {
{ private int _id;
    private int _id; private string _name;
    private string _name; private string _password;
    private string _password;
 //[PrimaryKey]特性指定Id作为主键
    //[PrimaryKey]特性指定Id作为主键 //用PrimaryKeyType.Identity来说明了主键的类型为自增型的
    //用PrimaryKeyType.Identity来说明了主键的类型为自增型的 [PrimaryKey(PrimaryKeyType.Identity, "ID")]
    [PrimaryKey(PrimaryKeyType.Identity, "ID")] public int Id
    public int Id {
    { get { return _id; }
        get { return _id; } set { _id = value; }
        set { _id = value; } }
    }
 [Property("LoginName")]
    [Property("LoginName")] public string Name
    public string Name {
    { get { return _name; }
        get { return _name; } set { _name = value; }
        set { _name = value; } }
    }
 //若属性名与列名一致可省略不写
    //若属性名与列名一致可省略不写 [Property]
    [Property] public string Password
    public string Password {
    { get { return _password; }
        get { return _password; } set { _password = value; }
        set { _password = value; } }
    } }
}四、编写配置文件App.config或web.config。由于ActiveRecord在底层封装了NHibernate,故配置文件的信息和NHibernate一致。
App.config:
 <?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="utf-8" ?> <configuration>
<configuration> <configSections>
    <configSections> <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
        <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" /> </configSections>
    </configSections> <activerecord>
    <activerecord> <config>
        <config> <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
            <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" /> <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" />
            <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" /> <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
            <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" />
            <add key="hibernate.connection.connection_string" value="UID=sa;Password=123456789;Initial Catalog=Castle;Data Source=EMMALEE" /> </config>
        </config> </activerecord>
    </activerecord> </configuration>
</configuration> <?xml version="1.0"?>
<?xml version="1.0"?> <configuration>
<configuration> <configSections>
    <configSections> <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/>
        <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/> </configSections>
    </configSections> <activerecord isWeb="true">
    <activerecord isWeb="true"> <config>
        <config> <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
            <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" /> <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" />
            <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" /> <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
            <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" />
            <add key="hibernate.connection.connection_string" value="UID=sa;Password=123456789;Initial Catalog=Castle;Data Source=EMMALEE" /> </config>
        </config> </activerecord>
    </activerecord> <system.web>
    <system.web> <compilation debug="true"/>
        <compilation debug="true"/> <authentication mode="Windows"/>
        <authentication mode="Windows"/> <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors>
        </customErrors> </system.web>
    </system.web> </configuration>
</configuration>
五、对象的CRUD操作。类ActiveRecordBas中定义了许多静态方法用于对象的CRUD操作,如:Create、Delete、DeleteAll、FindAll、FindAllByProperty、FindByPrimaryKey、Save等等一些静态方法。
1.Create操作
 User objUser = new User();
User objUser = new User(); objUser.Name = "jailu";
objUser.Name = "jailu"; objUser.Password = "123456789";
objUser.Password = "123456789";
 objUser.Create();
objUser.Create();2.Read操作
 User objUser = User.Find(1);    //检索主键ID为1的User对象
User objUser = User.Find(1);    //检索主键ID为1的User对象 string strName = objUser.Name;
string strName = objUser.Name; string strPassword = objUser.Password;
string strPassword = objUser.Password;3.Update操作
 User objUser = User.Find(1);    //检索主键ID为1的User对象
User objUser = User.Find(1);    //检索主键ID为1的User对象 objUser.Name = "EmmaLee";
objUser.Name = "EmmaLee"; objUser.Password = "987654321";
objUser.Password = "987654321";
 objUser.Update();
objUser.Update();4.Delete操作
 User objUser = User.Find(1);    //检索主键ID为1的User对象
 User objUser = User.Find(1);    //检索主键ID为1的User对象
 objUser.Delete();
objUser.Delete();5.完整的User类代码:
 using System;
using System; using System.Collections.Generic;
using System.Collections.Generic; using System.Text;
using System.Text; using System.Collections;
using System.Collections;
 using Castle.ActiveRecord;
using Castle.ActiveRecord; using Castle.ActiveRecord.Queries;
using Castle.ActiveRecord.Queries;
 namespace CastleTest
namespace CastleTest {
{ //为User类添加特性,其实就是告诉ActiveRecord,User类所对应的数据库中的数据表名为Users
    //为User类添加特性,其实就是告诉ActiveRecord,User类所对应的数据库中的数据表名为Users [ActiveRecord("Users")]
    [ActiveRecord("Users")] public class User : ActiveRecordBase
    public class User : ActiveRecordBase {
    { private int _id;
        private int _id; private string _name;
        private string _name; private string _password;
        private string _password;
 //[PrimaryKey]特性指定Id作为主键
        //[PrimaryKey]特性指定Id作为主键 //用PrimaryKeyType.Identity来说明了主键的类型为自增型的
        //用PrimaryKeyType.Identity来说明了主键的类型为自增型的 [PrimaryKey(PrimaryKeyType.Identity, "ID")]
        [PrimaryKey(PrimaryKeyType.Identity, "ID")] public int Id
        public int Id {
        { get { return _id; }
            get { return _id; } set { _id = value; }
            set { _id = value; } }
        }
 [Property("LoginName")]
        [Property("LoginName")] public string Name
        public string Name {
        { get { return _name; }
            get { return _name; } set { _name = value; }
            set { _name = value; } }
        }
 //若属性名与列名一致可省略不写
        //若属性名与列名一致可省略不写 [Property]
        [Property] public string Password
        public string Password {
        { get { return _password; }
            get { return _password; } set { _password = value; }
            set { _password = value; } }
        }
 public static void DeleteAll()
        public static void DeleteAll() {
        { 
             DeleteAll(typeof(User));
            DeleteAll(typeof(User)); }
        }
 public static IList FindAll()
        public static IList FindAll() {
        { return (IList)FindAll(typeof(User));
            return (IList)FindAll(typeof(User)); }
        }
 public static User Find(int id)
        public static User Find(int id) {
        { return (User)FindByPrimaryKey(typeof(User), id);
            return (User)FindByPrimaryKey(typeof(User), id); }
        }
 /// <summary>
        /// <summary> /// 根据LogonName查询User对象,在测试HQL查询时用到
        /// 根据LogonName查询User对象,在测试HQL查询时用到 /// </summary>
        /// </summary> /// <param name="LogonName">登录名</param>
        /// <param name="LogonName">登录名</param> /// <returns>User对象数组</returns>
        /// <returns>User对象数组</returns> public static User[] GetUsersByLogonName(string LogonName)
        public static User[] GetUsersByLogonName(string LogonName) {
        { SimpleQuery query = new SimpleQuery(typeof(User),@"from User user where user.Name = ?",LogonName);
            SimpleQuery query = new SimpleQuery(typeof(User),@"from User user where user.Name = ?",LogonName);
 return (User[])ExecuteQuery(query);
            return (User[])ExecuteQuery(query); }
        } }
    } }
}
六、表示层调用:
 private void button1_Click(object sender, EventArgs e)
private void button1_Click(object sender, EventArgs e) {
{ //初始化,获取连接字符串等信息
    //初始化,获取连接字符串等信息 IConfigurationSource source = System.Configuration.ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource;
    IConfigurationSource source = System.Configuration.ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource; ActiveRecordStarter.Initialize(source, typeof(User));
    ActiveRecordStarter.Initialize(source, typeof(User));
 User objUser = new User();
    User objUser = new User(); objUser.Name = "jailu";
    objUser.Name = "jailu"; objUser.Password = "123456789";
    objUser.Password = "123456789";
 objUser.Create();
    objUser.Create(); }
}至此,ActiveRecord的初步接触就算是完成了。
 
                    
                     
                    
                 
                    
                
 
     
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号