二,创建类
现在我们来依据表来创建类,这里你将看到有多方便。首先我们来从一个最简单的开始User类:
创建用户类
1、创建一个名字是User的类加上命名空间
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
public class User
{
}
}
2、现在来用ActiivRecordBase 中的ActiveRecordAttribute来扩展这个类:
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class User : ActiveRecordBase<User>
{
}
}
3、根据表中的列来增加相应的类的属性
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class User : ActiveRecordBase<User>
{
private int id;
private string username;
private string password;
private int Id
{
get { return id; }
set { id = value; }
}
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
}
}
4、 最后在类中添加标识标明在ActiveRecord中对应的是什么属性(即简单的属性映射到列,主键或关系)。在本例中Id标识为主键,其他的标识为普通属性:
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class User : ActiveRecordBase<User>
{
private int id;
private string username;
private string password;
public User()
{
}
public User(string username, string password)
{
this.username = username;
this.password = password;
}
[PrimaryKey]
private int Id
{
get { return id; }
set { id = value; }
}
[Property]
public string Username
{
get { return username; }
set { username = value; }
}
[Property]
public string Password
{
get { return password; }
set { password = value; }
}
}
}
就是这样简单,现在我们来分别创建Blog和Post类,过程和上面的一样,建议你自己试着写一下。
创建博客类
这个博客是很简单的,但是应该注意它是不完全的。我们仍然需要创建它和Post表的关联,但是这只需要一分钟:
namespace BlogSample
{
using System;
using System.Collections;
using Castle.ActiveRecord;
[ActiveRecord]
public class Blog : ActiveRecordBase<Blog>
{
private int id;
private String name;
private String author;
public Blog()
{
}
[PrimaryKey]
private int Id
{
get { return id; }
set { id = value; }
}
[Property]
public String Name
{
get { return name; }
set { name = value; }
}
[Property]
public String Author
{
get { return author; }
set { author = value; }
}
}
}
创始Post类
这个Post类也非常简单,但是它也不完整,我们需要把它和Blog类关联起来。
这里我也要注意它和其它的类一点不同,这个Contents 属性用了[Property(ColumnType="StringClob")]
这样做是因为我要把该列和类型是text的列绑定起来。
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class Post : ActiveRecordBase<Post>
{
private int id;
private String title;
private String contents;
private String category;
private DateTime created;
private bool published;
public Post()
{
created = DateTime.Now;
}
[PrimaryKey]
private int Id
{
get { return id; }
set { id = value; }
}
[Property]
public String Title
{
get { return title; }
set { title = value; }
}
[Property(ColumnType="StringClob")]
public String Contents
{
get { return contents; }
set { contents = value; }
}
[Property]
public String Category
{
get { return category; }
set { category = value; }
}
[Property]
public DateTime Created
{
get { return created; }
set { created = value; }
}
}
}
也许你会说这很容易,即使这是您第一次使用的ActiveRecord。同样的添加关系也不会太困难。