最近开始接触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的初步接触就算是完成了。