1. 程式人生 > >自己動手寫ORM框架(四):關係對映配置—Id屬性

自己動手寫ORM框架(四):關係對映配置—Id屬性

上一篇中完成了Table自定義屬性的功能,現在來完成Id,因為一張表最主要的是結構就是表名(Table name)、主鍵(Id)、列(Column)、主鍵生成策略。

Id自定義屬性的用法程式碼塊1-1:

[Table(name="Student")]
public class StudentEntity
{
    private string stuid;
    [Id(Name = "studentid", Strategy = GenerationType.SEQUENCE)]        
    public string Stuid
    {
        get
{ return stuid; } set { stuid = value; } } }

在Stuid屬性上[Id]就表示在StudentEntity實體類中,Stuid屬性欄位對應Student表中主鍵studentid,Name = “studentid”表示該屬性對應Student表中的studentid列名,如果Name值未指定或者為空,將預設為該屬性名稱和對應的Student表中的列名相同,都為Stuid。

Strategy = GenerationType.SEQUENCE表示主鍵生成方式,這裡是自動增長。

下面是自定義屬性Id的完整程式碼塊1-2:

using System;
using System.Collections.Generic;
using System.Text;

namespace System.Orm.CustomAttributes
{
    [AttributeUsage(AttributeTargets.Field|AttributeTargets.Property, 
        AllowMultiple = false, Inherited = false)]
    public class IdAttribute : Attribute
    {
        private string
_Name = string.Empty; private int _Strategy = GenerationType.INDENTITY; public string Name { get { return _Name; } set { _Name = value; } } public int Strategy { get { return _Strategy; } set { _Strategy = value; } } } }

在IdAttribute類上的屬性配置:
[AttributeUsage(AttributeTargets.Field|AttributeTargets.Property, AllowMultiple = false, Inherited = false)]

AttributeTargets.Field表示Id屬性可以配置在私有成員Field上,程式碼塊1-3:

[Table(name="Student")]
public class StudentEntity
{
    [Id(Name = "studentid", Strategy = GenerationType.SEQUENCE)]  
    private string stuid;                        

    //[Id(Name = "studentid", Strategy = GenerationType.SEQUENCE)]  
    public string Stuid
    {
        get { return stuid; }
        set { stuid = value; }
    }
}

這裡我們將[Id]加在了private string stuid;上面了,和加在屬性上是一樣的。
AttributeTargets.Property自然就是表示Id屬性可以配置在屬性Property上了,1-3中Stuid上註釋部分//[Id].
AttributeTargets.Field|AttributeTargets.Property中間加上 | 表示或的意思,即你可以配置在Field或者Property上都可以。

這裡還用到了一個GenerationType類,效果和列舉一樣,原始碼如下:

using System;
using System.Collections.Generic;
using System.Text;

namespace System.Orm.CustomAttributes
{
    public class GenerationType 
    {        
        public const int INDENTITY = 1;//自動增長
         public const int SEQUENCE = 2;//序列
         public const int TABLE = 3;//TABLE
         public const int GUID = 4;//GUID

        private GenerationType() { }//私有建構函式,不可被例項化物件
    }
}

好了,到這裡Id自定義屬性就完成了。