Castle学习系列(二)---ActiveRecord普通CRUD

上一篇已经介绍了ActiveRecord的基础配置,系统初始化的时候需要初始化基础配置,连接到数据库,之后才能进行增删改操作。

本章学习下具体的增删改步骤:

1.创建数据库

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

2.创建实体项目

用VS2012创建一个类库,引用必要的dll。然后创建实体类如下:

    [ActiveRecord("Users")]
    public class User : ActiveRecordBase
    {
        [PrimaryKey(PrimaryKeyType.Identity, "LogonID")]
        public int Id { get; set; }
       
        [Property("LogonName")]
        public string Name { get; set; }

        [Property("Password")]
        public string Password { get; set; }

        [Property("EmailAddress")]
        public string Address { get; set; }

        [Property("LastLogon")]
        public DateTime? LastLogon { get; set; }

        public static List QueryALl()
        {
            List userList = User.FindAll().ToList();
            return userList;
        }
    }
3.配置客户端连接环境并测试
基础环境配置可参照上一章,增删改代码如下:


新增

User user = new User();
user.Name = "张三";
user.Password = "123";
user.LastLogon = DateTime.Now;
user.Create();


修改

User user = User.Find(2);
user.Name = "李四";
user.Update();


删除

User user = User.Find(4);
user.Delete();

查询

List userList = User.QueryALl();
string useMsg = "";
foreach (User user in userList)
{
      useMsg += user.Id + "," + user.Name + Environment.NewLine;
}
MessageBox.Show(useMsg);


你可能感兴趣的:(Castle框架学习)