最近看了C#的反射基制,在想到C#的特性我觉的用C#建一套从对象到数据库表的映射的框架是非常好,不用在像NHIBERNATE那样要写烦琐的配置文件.
用特性建立对对象间的关联
特性定义:
[Serializable, AttributeUsage(AttributeTargets.Class, AllowMultiple=true)] public class AssociationAttribute : Attribute { // Fields private bool cascadeDelete; private enumERType erType; private Type targetType; // Methods public AssociationAttribute(Type targetType, enumERType erType); // Properties public bool CascadeDelete { get; set; } public enumERType ERType { get; set; } public Type TargetType { get; set; } }
建立一个对象应用特性
[Serializable]
[Association(typeof(Image), enumERType.R1M, CascadeDelete = true)]
[Association(typeof(File), enumERType.R1M, CascadeDelete = true)]
[Association(typeof(Flash), enumERType.R1M, CascadeDelete = true)]
[Association(typeof(Comment), enumERType.R1M, CascadeDelete = true)]
[Association(typeof(TAG), enumERType.RMM)]
public class Article : DBObject
{
[DBType(enumDBType.Char, Length = 256)]
string title;[DBType(enumDBType.Char, Length = 256)]
string keywords;[DBType(enumDBType.Text)]
string content;DateTime updateTime;
/// <summary>
/// Initializes a new instance of the <see cref="Article"/> class.
/// </summary>
public Article()
{
title = string.Empty;
keywords = string.Empty;
content = string.Empty;
updateTime = DateTime.Now;
}#region Attributes
/// <summary>
///
/// </summary>
public string Title
{
get { return title; }
set { title = value; }
}/// <summary>
///
/// </summary>
public string Keywords
{
get { return keywords; }
set { keywords = value; }
}/// <summary>
///
/// </summary>
public string Content
{
get { return content; }
set { content = value; }
}/// <summary>
///
/// </summary>
public System.DateTime UpdateTime
{
get { return updateTime; }
set { updateTime = value; }
}
#endregion
#region ClassMetaData
public new class Meta
{
public static string Guid = "CMS_Article_guid";public static string Title = "CMS_Article_title";
public static string Keywords = "CMS_Article_keywords";
public static string Content = "CMS_Article_content";
public static string UpdateTime = "CMS_Article_updateTime";
public static string Dbstate = "CMS_Article_dbstate";}
}
#endregion其中META class 是冗余字段对应数据库的列名
应用反射获得对象间的关联
建立对象的表
浙公网安备 33010602011771号