自己动手写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自定义属性就完成了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若行若冲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值