C# ORM從物件到資料庫表的對映

iDotNetSpace發表於2009-12-07

最近看了C#的反射基制,在想到C#的特性我覺的用C#建一套從物件到資料庫表的對映的框架是非常好,不用在像NHIBERNATE那樣要寫煩瑣的配置檔案.

 

用特性建立對物件間的關聯

特性定義:

[Serializable, AttributeUsage(AttributeTargets.Class, AllowMultiple=true)]
public class AssociationAttribute : Attribute
{
    // Fields
    private bool cascadeDelete;
    private enumERType erType;
    private Type targetType;

    // Methods
    public AssociationAttribute(Type targetType, enumERType erType);

    // Properties
    public bool CascadeDelete { get; set; }
    public enumERType ERType { get; set; }
    public Type TargetType { get; set; }
}
建立一個物件應用特性

 [Serializable]
    [Association(typeof(Image), enumERType.R1M, CascadeDelete = true)]
    [Association(typeof(File), enumERType.R1M, CascadeDelete = true)]
    [Association(typeof(Flash), enumERType.R1M, CascadeDelete = true)]
    [Association(typeof(Comment), enumERType.R1M, CascadeDelete = true)]
    [Association(typeof(TAG), enumERType.RMM)]
    public class Article : DBObject
    {
        [DBType(enumDBType.Char, Length = 256)]
        string title;

        [DBType(enumDBType.Char, Length = 256)]
        string keywords;

        [DBType(enumDBType.Text)]
        string content;

        DateTime updateTime;

        ///


        /// Initializes a new instance of the class.
        ///

        public Article()
        {
            title = string.Empty;
            keywords = string.Empty;
            content = string.Empty;
            updateTime = DateTime.Now;
        }

        #region Attributes
        ///


        ///
        ///

        public string Title
        {
            get { return title; }
            set { title = value; }
        }

        ///


        ///
        ///

        public string Keywords
        {
            get { return keywords; }
            set { keywords = value; }
        }

        ///


        ///
        ///

        public string Content
        {
            get { return content; }
            set { content = value; }
        }

        ///


        ///
        ///

        public System.DateTime UpdateTime
        {
            get { return updateTime; }
            set { updateTime = value; }
        }
        #endregion
        #region ClassMetaData
        public new class Meta
        {
            public static string Guid = "CMS_Article_guid";

            public static string Title = "CMS_Article_title";
            public static string Keywords = "CMS_Article_keywords";
            public static string Content = "CMS_Article_content";
            public static string UpdateTime = "CMS_Article_updateTime";
            public static string Dbstate = "CMS_Article_dbstate";

        }

}
        #endregion

其中META. class 是冗餘欄位對應資料庫的列名

應用反射獲得物件間的關聯

建立物件的表

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-621839/,如需轉載,請註明出處,否則將追究法律責任。

相關文章