自己动手写ORM框架(三):关系映射配置—Table属性

在上一篇随笔中已经完成了ADO.NET操作数据库的封装,并已经支持多数据库,只需要在配置文件中指定数据库类型即可,本节主要完成对象与数据库表的关系映射配置。

下面看表名的映射配置代码块1-1:

[Table(Name="Student")]  
public class StudentEntity  
{  
    //...........省略  
}  

在类上面用[Table(name = ”Student”)]属性来配置,表示该实体类StudentEntity与数据库中的Student表进行关系映射。
Table属性需要自己编写

TableAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Rizi.Frame.Orm.Core
{
    /// <summary>
    /// ORM:数据表映射属性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    public class TableAttribute : Attribute
    {
        /// <summary>
        /// 使用数据表名初始化TableMapping属性。
        /// </summary>
        /// <param name="name">数据库表名</param>
        public TableAttribute(string name);

        /// <summary>
        /// 使用数据表名和描述信息初始化TableMapping属性
        /// </summary>
        /// <param name="name">数据库表名</param>
        /// <param name="description">描述信息</param>
        public TableAttribute(string name, string description);

        /// <summary>
        /// 描述信息
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// 数据库表名
        /// </summary>
        public string Name { get; set; }
    }
}

上面代码中我们编写TableAttribute自定义属性类,然后继承Attribute自定义属性基类,在具体使用的时候我们只需在需要配置属性的类上加[Table(Name=”你要指定的表名”, “描述信息”)]。这里的TableAttribute省略了后面的Attribute,用Table即可.NET会根据Table名称+Atrribute去查找TableAttribute类。

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]

这段属性配置表示TableAttribute属性类的用法配置,

1) AttributeTargets.Class表示只可用于类,所以使用时把该属性加载类的上面,如代码块1-1
2) AllowMultiple 表示能否为一个元素指定多个属性示例,在这里比如在StudentEntity上是否可以配置多次Table属性,我们设置false即只可配置一次。
3) Inherited 表示Table属性可否被继承,这里设置false即不可被继承。

在TableAttribute属性类中定义了Name公有属性,用于指定Table属性所配置的实体所对应的数据库中表名。

这里Table属性到这里已经完成,下一篇中将继续介绍自定义属性:
IdAttribute (用于指定实体类中哪一个属性字段对应数据库表中的主键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、付费专栏及课程。

余额充值