Gentle文档(一) 基本示例-本地化,非汉化

一个简单的User类
public class User
{
    private int userId;
    private string userName;

    public User( int userId, string userName )
    {
        this.userId = userId;
        this.userName = userName;
    }

    public int Id
    {
        get{ return userId; }
        set{ userId = value; }
    }

    public string Name
    {
        get{ return userName; }
        set{ userName = value; }
    }
}


  为了让这个类可以持久化,我们使用Gentle.Net框架特性来标识出类作为一个技久化对象。标识了这些特性的类,能够进行保存(包括任何自定义名称的类)

持久化版本的User类
[TableName("Users")]
public class User
{
    private int userId;
    private string userName;

    public User( int userId, string userName )
    {
        this.userId = userId;
        this.userName = userName;
    }

    [TableColumn("UserId"), PrimaryKey]
    public int Id
    {
        get{ return userId; }
        set{ userId = value; }
    }

    [TableColumn(NotNull=true)]
    public string Name
    {
        get{ return userName; }
        set{ userName = value; }
    }
}



  你并不需要添加任何代码,只需要添加特性的标识就行了。


  请注意是怎么映射属性到UserId列的,如果映射时,需要指明映射到数据库中的列名时,才有必要写清,否则默认情况下,使用的是属性名称作为映射到数据库中的列名。

  如果要映射到现有的数据库表的话,可以使用工具(MyGenerationCodeSmith自动生成Gentle的代码。

下面的代码说明了我们如何操作User类

调用代码:保存与读取
User user = new User( 42, "Ford Prefect" );
Broker.Persist( user ); // save the user to the database
Key key = new Key( typeof(User), true, "Id", 42 ); // create a key with a single selection criteria value
user = Broker.RetrieveInstance( typeof(User), key ) as User; // load the specified user from the database


最终的User类
[TableName]
public class User : Persistent
{
    private int userId;
    private string userName;

    // this is used by clients to construct new users
    public User( string userName ) : this( 0, userName ) {}

    // this is used by Gentle to reconstruct objects read from the database
    public User( int userId, string userName )
    {
        this.userId = userId;
        this.userName = userName;
    }

    // this is used by client to fetch users from the database
    static public User Retrieve( int userId )
    {
        Key key = new Key( typeof(User), true, "Id", userId );
        return Broker.RetrieveInstance( typeof(User), key ) as User;
    }

    [TableColumn("UserId"), PrimaryKey(AutoGenerated=true)]
    public int Id
    {
        get{ return userId; }
        set{ userId = value; }
    }

    [TableColumn(NotNull=true)]
    public string Name
    {
        get{ return userName; }
        set{ userName = value; }
    }
}
posted @ 2005-03-11 11:02  一根神棍研古今  阅读(1423)  评论(0编辑  收藏  举报
Web Counter