最近开始接触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
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
//![](https://www.cnblogs.com/Images/dot.gif)
}
4.用[ActiveRecrod()]为类添加特性,指出User类对应的数据表是Users:
[ActiveRecord("Users")]
public class User : ActiveRecordBase
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
//![](https://www.cnblogs.com/Images/dot.gif)
}
5.用[Property()]为属性添加特性,指出属性对应数据表中的列:
[ActiveRecord("Users")]
public class User : ActiveRecordBase
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
private int _id;
private string _name;
private string _password;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
//[PrimaryKey]特性指定Id作为主键
//用PrimaryKeyType.Identity来说明了主键的类型为自增型的
[PrimaryKey(PrimaryKeyType.Identity, "ID")]
public int Id
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return _id; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ _id = value; }
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
[Property("LoginName")]
public string Name
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return _name; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ _name = value; }
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
//若属性名与列名一致可省略不写
[Property]
public string Password
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return _password; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
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>
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
五、对象的CRUD操作。类ActiveRecordBas中定义了许多静态方法用于对象的CRUD操作,如:Create、Delete、DeleteAll、FindAll、FindAllByProperty、FindByPrimaryKey、Save等等一些静态方法。
1.Create操作
User objUser = new User();
objUser.Name = "jailu";
objUser.Password = "123456789";
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
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";
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
objUser.Update();
4.Delete操作
User objUser = User.Find(1); //检索主键ID为1的User对象
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
objUser.Delete();
5.完整的User类代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
using Castle.ActiveRecord;
using Castle.ActiveRecord.Queries;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
namespace CastleTest
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
//为User类添加特性,其实就是告诉ActiveRecord,User类所对应的数据库中的数据表名为Users
[ActiveRecord("Users")]
public class User : ActiveRecordBase
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
private int _id;
private string _name;
private string _password;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
//[PrimaryKey]特性指定Id作为主键
//用PrimaryKeyType.Identity来说明了主键的类型为自增型的
[PrimaryKey(PrimaryKeyType.Identity, "ID")]
public int Id
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return _id; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ _id = value; }
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
[Property("LoginName")]
public string Name
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return _name; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ _name = value; }
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
//若属性名与列名一致可省略不写
[Property]
public string Password
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return _password; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ _password = value; }
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public static void DeleteAll()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
DeleteAll(typeof(User));
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public static IList FindAll()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return (IList)FindAll(typeof(User));
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public static User Find(int id)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return (User)FindByPrimaryKey(typeof(User), id);
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 根据LogonName查询User对象,在测试HQL查询时用到
/// </summary>
/// <param name="LogonName">登录名</param>
/// <returns>User对象数组</returns>
public static User[] GetUsersByLogonName(string LogonName)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
SimpleQuery query = new SimpleQuery(typeof(User),@"from User user where user.Name = ?",LogonName);
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
return (User[])ExecuteQuery(query);
}
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
六、表示层调用:
private void button1_Click(object sender, EventArgs e)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
//初始化,获取连接字符串等信息
IConfigurationSource source = System.Configuration.ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource;
ActiveRecordStarter.Initialize(source, typeof(User));
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
User objUser = new User();
objUser.Name = "jailu";
objUser.Password = "123456789";
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
objUser.Create();
}
至此,ActiveRecord的初步接触就算是完成了。