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列的,如果映射时,需要指明映射到数据库中的列名时,才有必要写清,否则默认情况下,使用的是属性名称作为映射到数据库中的列名。

  如果要映射到现有的数据库表的话,可以使用工具(MyGenerationCodeSmithlinkext7.gif自动生成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; }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值