C# ORM从对象到数据库表的映射

探讨使用C#反射机制创建对象与数据库表映射框架的可能性,通过自定义特性简化ORM映射配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近看了C#的反射基制,在想到C#的特性我觉的用C#建一套从对象到数据库表的映射的框架是非常好,不用在像NHIBERNATE那样要写烦琐的配置文件.

 

用特性建立对对象间的关联

特性定义:

[, (., =)]
   : 
{
    
      ;
      ;
      ;

    
     ( targetType,  erType);

    
       { ; ; }
       { ; ; }
       { ; ; }
}
建立一个对象应用特性
 
 

 [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/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/12639172/viewspace-621839/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值