在第一篇《一步步实现自己的ORM(一)》里,我们用反射获取类名、属性和值,我们用这些信息开发了简单的INSERT方法,在上一篇文章里我们提到主键为什么没有设置成自增长类型,单单从属性里我们无法识别哪个是主键,今天我们用Attribute来标识列,关于Attribute,引用MSDN里描述

     MADN的定义为:公共语言运行时允许添加类似关键字的描述声明,叫做attributes, 它对程序中的元素进行标注,如类型、字段、方法和属性等。Attributes和Microsoft .NET Framework文件的元数据(metadata)保存在一起,可以用来向运行时描述你的代码,或者在程序运行的时候影响应用程序的行为。     我们简单的总结为:定制特性attribute,本质上是一个类,其为目标元素提供关联附加信息,并在运行期以反射的方式来获取附加信息。 

简单来说Attribute就是描述类、方法、属性参数等信息的。

可参考《浅析C#中的Attribute

 

在这里我们定义2个Attribute,用来描述表和字段。

    [AttributeUsage(AttributeTargets.Class)]
    class TableAttribute : Attribute
    {
        /// <summary>
        /// 表名
        /// </summary>
        public string Name { get; private set; }

        public TableAttribute(string name)
        {
            this.Name = name;
        }
    }

    [AttributeUsage(AttributeTargets.Property)]
    class ColumnAttribute : Attribute
    {
        /// <summary>
        /// 是否为数据库自动生成
        /// </summary>
        public bool IsGenerated { get; set; }

        /// <summary>
        /// 列名
        /// </summary>
        public string Name { get; private set; }

        public ColumnAttribute(string name)
        {
            this.Name = name;
        }
    }
View Code

相关文章:

  • 2022-12-23
  • 2021-11-14
  • 2022-12-23
  • 2022-12-23
  • 2021-08-05
  • 2019-02-13
  • 2021-07-24
  • 2021-12-22
猜你喜欢
  • 2021-05-16
  • 2021-08-18
  • 2021-05-24
  • 2021-11-21
  • 2021-10-20
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案