自己动手写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)

猜你喜欢

转载自blog.csdn.net/coolhe21cn/article/details/79076088