代码改变世界

Castle.ActiveRecord 学与练[1]

2008-04-01 14:35  土星的狗狗  阅读(2393)  评论(11编辑  收藏  举报

    Castle.ActiveRecord
    空闲下来了,回想当时没有完成的任务,Castle的学习就是其中一项.
    在网上找了许多的资料,其中Terrylee老师的算是比较经典的.打算看一点做一点,一步一步的走~遇到的问题写出来,供大家参考讨论.
Castleproject.Org官网上FAQ里就"What is Castle Project?"说道:"An umbrella for projects that share the same goal: boost productivity while promoting good code and good design. ".对~good code and good design,为了这个CODE和DESIGN,我们来一点一点的挖掘Castle里的秘密吧.

第一部分,紧跟
Terrylee老师的步伐,我先开始通过Castle.ActiveRecord了解Castle.
    开始,先跟大家说一下, Castle.ActiveRecord是Castle中提供的一个数据访问框架,它在底层封装了NHibernate的操作,使用特性来代替映射文件,这样咱们就不必再去为编写.hbm.xml文件而费心了(虽然有了代码生成器).
    
教程用例将直接套用Terrylee老师的教程用例,并在里面添加上我的一些相应经历,请大家谅解(自己编写例子真的很烦啊,呵呵)
    练习数据表Users:

CREATE TABLE [dbo].[Users] (
    
[LogonID] [int] IDENTITY (11NOT NULL
 ,
    
[LogonName] [varchar] (40) COLLATE Chinese_PRC_CI_AS NULL
 ,
    
[Password] [varchar] (20) COLLATE Chinese_PRC_CI_AS NULL
 ,
    
[EmailAddress] [varchar] (40) COLLATE Chinese_PRC_CI_AS NULL
 ,
    
[LastLogon] [datetime] NULL
 
ON [PRIMARY]

GO

第二部分,实体类的编码.

 1using System;
 2using
 System.Collections.Generic;
 3using
 System.Text;
 4using
 Castle.ActiveRecord;
 5using
 System.Collections;
 6using
 Castle.ActiveRecord.Framework;
 7

 8namespace
 cn.Guy.Training.User
 9
{
10    
/// <summary>
11    /// UserEntity 的摘要说明。
12    /// </summary>

13    [ActiveRecord("Users")]
14    public class
 UserEntity : ActiveRecordBase
15    
{
16        private int
 _id;
17

18        private string
 _name;
19

20        private string
 _password;
21

22        private string
 _emailAddress;
23

24        private
 DateTime _lastLogon;
25

26        [PrimaryKey(PrimaryKeyType.Identity, "LogonID"
)]
27        public int
 Id
28        
{
29            get return _id; }

30            set { _id = value; }
31        }

32
33        [Property("LogonName"
)]
34        public string
 Name
35        
{
36            get return _name; }

37            set { _name = value; }
38        }

39
40        [Property("Password"
)]
41        public string
 Password
42        
{
43            get return _password; }

44            set { _password = value; }
45        }

46
47        [Property("EmailAddress"
)]
48        public string
 Address
49        
{
50            get return _emailAddress; }

51            set { _emailAddress = value; }
52        }

53
54        [Property("LastLogon"
)]
55        public
 DateTime LastLogon
56        
{
57            get return _lastLogon; }

58            set { _lastLogon = value; }
59        }

60
61        public static void
 DeleteAll()
62        
{
63            DeleteAll(typeof
(UserEntity));
64        }

65
66        public static
 IList FindAll()
67        
{
68            return (IList)FindAll(typeof
(UserEntity));
69        }

70
71        public static UserEntity Find(int
 id)
72        
{
73            return (UserEntity)FindByPrimaryKey(typeof
(User), id);
74        }

75
76        public static void
 Delete(UserEntity userEntity)
77        
{
78
            userEntity.DeleteAndFlush();
79        }

80    }

81}

    首先我们来看代码前端类声明的部分:
    [ActiveRecord("Users")]
    public class UserEntity : ActiveRecordBase
    UserEntity类继承于ActiveRecordBase,并且为UserEntity类添加了[ActiveRecord("Users")]的特性,意指UserEntity所对应的数据库表为Users.
    然后再来看属性定义部分:
    [PrimaryKey(PrimaryKeyType.Identity, "LogonID")]
    public int Id
    {
         get { return _id; }
         set { _id = value; }
    }
    Id这个属性返回值为INT类型,并且为它添加了一个
[PrimaryKey(PrimaryKeyType.Identity, "LogonID")]的特性,意指Id所对应的数据库表字段为LogonID,主键且为自增类型.
    注:如果属性名和字段名一致,[Property()]中可为空.
    最后,就练习中写到的几个静态方法向大家说明一下:
    从ActiveRecordBase里可以直接继承到一些最基本的方法,比如:Create()Update()Delete()Save()及相应扩展方法.
    咱们通过这些基本的方法,对Users这个表可以进行INSERT,UPDATE,SELECT操作,以达到练习的目的.
    在执行这些方法前,需要对ActiveRecord进行数据库配置,在这里,我只介绍一种方法,也是最常用的方法:配置文件.

 1<?xml version="1.0" encoding="utf-8" ?>
 2<configuration>
 3    <configSections>
 4        <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
 5    </configSections>
 6    <activerecord>
 7        <config>
 8            <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
 9            <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" />
10            <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
11            <add key="hibernate.connection.connection_string" value="UID=sa;Password=love;Initial Catalog=CastleTraining;Data Source=GUYZ\GUYZ2000" />
12        </config>
13    </activerecord>
14</configuration>

这样,实体部分的编码就等于告一段落了.
第三部分:测试
    我是新建了一应用程序进行测试,因为我个人更喜欢界面化的操作,交互的快感,呵呵!
    

 1using System;
 2using
 System.Collections.Generic;
 3using
 System.ComponentModel;
 4using
 System.Data;
 5using
 System.Drawing;
 6using
 System.Text;
 7using
 System.Windows.Forms;
 8using
 Castle.ActiveRecord.Framework;
 9using
 Castle.ActiveRecord;
10using
 System.Collections;
11

12namespace
 cn.Guy.Training.User
13
{
14    public partial class
 User : Form
15    
{
16        public
 User()
17        
{
18
            InitializeComponent();
19            IConfigurationSource source = System.Configuration.ConfigurationSettings.GetConfig("activerecord"as
 IConfigurationSource;
20            ActiveRecordStarter.Initialize(source, typeof
(UserEntity));
21        }

22
23        private void GetUserList_Click(object
 sender, EventArgs e)
24        
{
25            IList users =
 UserEntity.FindAll();
26            textBox1.Text = ""
;
27            for (int i = 0; i < users.Count; i++
)
28            
{
29                textBox1.Text += ((UserEntity)users[i]).Id+((UserEntity)users[i]).Name + " "
;
30            }

31        }

32
33        private void AddNewUser_Click(object
 sender, EventArgs e)
34        
{
35            UserEntity users = new
 UserEntity();
36

37            users.Name = "Guy"
;
38            users.Password = "guy"
;
39            users.Address = "lguyss@foxmail.com"
;
40            users.LastLogon =
 DateTime.Now;
41

42
            users.Create();
43        }

44
45        private void DeleteUser_Click(object
 sender, EventArgs e)
46        
{
47            UserEntity users = new
 UserEntity();
48

49            users.Id = int
.Parse(textBox1.Text.Trim());
50
            users.Delete();
51        }

52
53        private void Quit_Click(object
 sender, EventArgs e)
54        
{
55
            Application.Exit();
56        }

57    }

58}

    大家可以看到,我在这个类的构造函数里写了这样两个语句:
    IConfigurationSource source = System.Configuration.ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource;
    ActiveRecordStarter.Initialize(source, typeof(UserEntity));
    从配置文件里读取配置,最后对ActiveRecordStarter进行初始化,就可以进行方法的执行了.
    
    小弟第一次发系列文章,还请高手们多多见谅.
    谢谢
Terrylee老师的教程对我的帮助.
    QQ:22566547;
    MSN:LGUYSS@GMAIL.COM;
    SITE:WWW.MOBILEBETA.NET
    
练习源码下载

Creative Commons License
It's my life