现在到了创建对应到数据表的类实体的时候了,这里你会发现这是多么简单。首先我们从最简单的一个开始User类:
创建User类:
1、 创建一个空的User类,添加using语句
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
public class User
{
}
}
2、现在让类继承ActiveRecordBase并且使用AcriveRecordAttribute属性
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class User : ActiveRecordBase
{
}
}
3、添加字段以及相应的对数据库列的属性
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class User : ActiveRecordBase
{
private int id;
private string username;
private string password;
public 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、最后添加属性告知AcriveRecord属性是什么(例如:简单的属性,主键,关联等)。在这里,我只需要把ID标示为主键,其他都是简单属性:
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class User : ActiveRecordBase
{
private int id;
private string username;
private string password;
[PrimaryKey]
public 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类
Blog类很直接。记住它并不是完整的,我们需要在它和Post之间添加一个链接。一会儿我们就添加
namespace BlogSample
{
using System;
using System.Collections;
using Castle.ActiveRecord;
[ActiveRecord]
public class Blog : ActiveRecordBase
{
private int id;
private String name;
private String author;
public Blog()
{
}
[PrimaryKey]
public 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
{
private int id;
private String title;
private String contents;
private String category;
private DateTime created;
private bool published;
public Post()
{
created = DateTime.Now;
}
[PrimaryKey]
public 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; }
}
}
}
你应该会认同这非常简单,即使这是你第一次使用AcriveRecord。添加关联也不会很困难。