自己动手写ORM框架(三):关系映射配置—Table属性
在上一篇随笔中已经完成了ADO.NET操作数据库的封装,并已经支持多数据库,只需要在配置文件中指定数据库类型即可,本节主要完成对象与数据库表的关系映射配置。
下面看表名的映射配置代码块1-1:
[Table(Name="Student")]
public class StudentEntity
{
//...........省略
}
在类上面用[Table(name = ”Student")]属性来配置,表示该实体类StudentEntity与数据库中的Student表进行关系映射。
Table属性需要自己编写,代码块1-2:
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Orm.CustomAttributes
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class TableAttribute : Attribute
{
private string _Name = string.Empty;
public TableAttribute() {}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
}
上面代码中我们编写TableAttribute自定义属性类,然后继承Attribute自定义属性基类,在具体使用的时候我们只需在需要配置属性的类上加[Table(Name="你要指定的表名")]。这里的TableAttribute省略了后面的Attribute,用Table即可.NET会根据Table名称+Atrribute去查找TableAttribute类。
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
这段属性配置表示TableAttribute属性类的用法配置,
AttributeTargets.Class表示只可用于类,所以使用时把该属性加载类的上面,如代码块1-1
AllowMultiple 表示能否为一个元素指定多个属性示例,在这里比如在StudentEntity上是否可以配置多次Table属性,我们设置false即只可配置一次。www.zzzyk.com
Inherited 表示Table属性可否被继承,这里设置false即不可被继承。
在TableAttribute属性类中定义了Name公有属性,用于指定Table属性所配置的实体所对应的数据库中表名。
这里Table属性到这里已经完成,下一篇中将继续介绍自定义属性:
IdAttribute (用于指定实体类中哪一个属性字段对应数据库表中的主键ID)
补充:软件开发 , Java ,