现在的位置: 首页 > 综合 > 正文

Castle ActiveRecord学习实践(9):使用ActiveRecord的一些技巧

2012年09月15日 ⁄ 综合 ⁄ 共 2621字 ⁄ 字号 评论关闭

摘要:本文将会介绍使用ActiveRecord中的一些技巧。

 

主要内容

1.由实体类生成数据表

2.运行存在的SQL脚本

3.使用空属类型

4.使用枚举类型的属性

5.使用NHibernate中的日志记录

 

一.由实体类生成数据表

在前面所用到的例子中我们都是先有数据表结构,然后才有实体类,然而这会让很多朋友认为ORM怎么变成了ROM了,其实这只是我们平时的一个开发时的习惯问题,ActiveRecord是支持先有实体类,再由实体类生成数据库表。只不过我们可以在开发中根据项目的实际情况在这两种之间选择。看下面的代码,要生成数据库表结构,在实体类中需要多提供一些信息,是否为空,字段长度等。

[ActiveRecord("Blogs")]

public class Blog : ActiveRecordBase

{

    
private int _id;

    
private String _name;

    
private String _author;

 

    [PrimaryKey(PrimaryKeyType.Native, 
"blog_id")]

    
public int Id

    
{

        
get return _id; }

        
set { _id = value; }

    }


 

    [Property(
"blog_name", NotNull=true, Length=25)]

    
public String Name

    
{

        
get return _name; }

        
set { _name = value; }

    }


 

    [Property(
"blog_author", NotNull=true, Length=50)]

    
public String Author

    
{

        
get return _author; }

        
set { _author = value; }

    }


}

要生成数据库表需要调用ActiveRecordStarter.CreateSchema()方法就可以了。

public void Initli()

{

    XmlConfigurationSource source 
= new XmlConfigurationSource("MyConfig.xml");

    

    ActiveRecordStarter.Initialize( source, 
typeof(Blog),typeof(Post),typeof(Custom));

    ActiveRecordStarter.CreateSchema();

}

这里需要注意两点:

 

1.生成数据库表时只有当该表不存在时ActiveRecord才会生成,否则表如果存在ActiveRecord不会做任何事情,也不会报任何错误。

2.如果在实体类中没有指定字段的长度和是否为空,则默认生成的字段是允许为空的,且字符类生成后的字段类型为Nvarchar,长度为255

 

二.运行存在的SQL脚本

有时候我们会想在ActiveRecord框架启动时运行一个已经存在的SQL脚本来生成数据库表结构,ActiveRecord同样也提供了这样的功能,通过调用ActiveRecordStarter.CreateSchemaFromFile()来实现。示例代码如下:

public void Initli()

{

    XmlConfigurationSource source 
= new XmlConfigurationSource("MyConfig.xml");

    

    ActiveRecordStarter.Initialize( source, 
typeof(Blog));

 

    ActiveRecordStarter.CreateSchemaFromFile(
"MySqlScript.sql");

}

 

三.使用空属类型

在进行数据库操作时,有时候需要进行空值的处理,在ActiveRecord中给我们提供了一组空属类型,可以方便的进行处理,比如可以这样写属性:

[Property]

public NullableDateTime CreatedDate

{

    
get return _createdDate; }

    
set { _createdDate = value; }

}


 

[Property]

public NullableInt32 Count

{

    
get return _count; }

    
set { _count = value; }

}

看一下ActiveRecord提供的空属类型与实际类型对照表

CLR Basic Type

Nullable Type

System.Boolean

Nullables.NullableBoolean

System.Byte

Nullables.NullableByte

System.Char

Nullables.NullableChar

System.DateTime

Nullables.NullableDateTime

System.Decimal

Nullables.NullableDecimal

System.Double

Nullables.NullableDouble

System.Guid

Nullables.NullableGuid

System.Int16

Nullables.NullableInt16

System.Int32

Nullables.NullableInt32

System.Int64

Nullables.NullableInt64

System.SByte

Nullables.NullableSByte

System.Single

Nullables.NullableSingle

注意在使用空属类型时需要添加以下引用

Nullables.dll

Nullables.NHibernate.dll

 

四.使用枚举类型属性

ActiveRecord中我们可以定义一个属性的类型为枚举类型,示例代码:

public class Post : ActiveRecordBase

{

    
//

 

    
private StatusType _status_type_id;

 

    
public 

抱歉!评论已关闭.