Castle ActiveRecord学习实践(3):映射基础
2006-04-06 08:28:00
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://terrylee.blog.51cto.com/342737/67658 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
摘要:本文详细介绍了ActiveRecord中的基本映射,对于关联映射会在后续文章中通过一些具体的实例来说明。
主要内容
简单映射
1.ActiveRecordAttribute
2. PrimaryKeyAttribute
3.CompositeKeyAttribute
4.PropertyAttribute
5.FieldAttribute
一.ActiveRecordAttribute
每一个实体类都必须继承于基类ActiveRecordBase,并在实体类上设置特性ActiveRecordAttribute,示例代码
//指定数据库表名![]() [ActiveRecord("Blogs")]![]() public class Blog : ActiveRecordBase![]() {![]() //![]() }![]() //不指定数据库表名![]() [ActiveRecord]![]() public class Blog : ActiveRecordBase![]() {![]() //![]() }
二.PrimaryKeyAttribute
在实体类中,通过PrimaryKeyAttribute来指定表的主键,示例代码
//指定主键字段名![]() [ActiveRecord()]![]() public class Blog : ActiveRecordBase![]() {![]() private int id;![]() ![]() [PrimaryKey("blog_id")]![]() public int Id![]() {![]() get { return id; }![]() set { id = value; }![]() }![]() }![]() //不指定主键字段名![]() [ActiveRecord()]![]() public class Blog : ActiveRecordBase![]() {![]() private int id;![]() ![]() [PrimaryKey]![]() public int Id![]() {![]() get { return id; }![]() set { id = value; }![]() }![]() }![]() PrimaryKeyAttribute说明
主键的生成方式介绍
三.CompositeKeyAttribute
如果使用组合键,需要我们自定义一个类来作为主键属性的类型。示例代码
[PrimaryKey]![]() public MyCompositeKey ID![]() {![]() get { return _key; }![]() set { _key = value; }![]() }对于组合键类,除了需要加上CompositeKey特性之外,它还需要是可序列化的,并且要求实现Equals和GetHashCode方法。ActiveRecord官方网站上提供的一个组合键的示例程序如下: [CompositeKey, Serializable]![]() public class MyCompositeKey![]() {![]() private string _keyA;![]() private string _keyB;![]() ![]() [KeyProperty]![]() public virtual string KeyA![]() {![]() get { return _keyA; }![]() set { _keyA = value; }![]() }![]() ![]() [KeyProperty]![]() public virtual string KeyB![]() {![]() get { return _keyB; }![]() set { _keyB = value; }![]() }![]() ![]() public override string ToString()![]() {![]() ![]() |








}
}