手把手教你寫ORM(六)
最近越來越不知道該吃什么了。唉。
現在到了比較激動的地方了,ORM,說白了最主要的工作就是將對象和數據庫表格的映射建立起來。
這里我們就不用XML文件來配置了,第一會使配置文件結構變復雜加大解析難度,第二我來看看另外一種做映射的方法。
這里介紹一下.NET的Attribute,在早些時候被翻譯作屬性,和property混淆了。現在一般都翻譯為特性或特征,它可以給一個類或者類的成員附加一些額外的特征或者功能。在.NET里面的System.Arribute作為其基類,所有繼承自他的,并且類名以Attribute結尾的類型都可以作為Attribute實用,這里有一個約束,定義的時侯類名要以Attribute結尾,但是使用的時候要去掉Attibute。.NET類庫預定義了很多的特性來實現很多的功能,這里我們通過Attribute類來標示類成員的特性,并且通過反射來獲取來標示類成員與數據庫的映射。
首先我們通過一個例子來看看Attribute的特性
執行結果自然是一個異常,異常的message是error:can not run this method!
ok,現在是否明白了它的工作原理?還有點暈?暈不要緊,做了再說。
class TestAttribute:System.Attribute
{
public TestAttribute(string message)
{
throw new Exception("error:"+message);
}
}
class Tester
{
[Test("Can not run this method!")]
public void Cannotrun()
{
}
public static Main(sting[] args)
{
Tester t=new Tester();
t.Cannotrun();
}
}
我們現在就是來構造一個Attribute的類來存儲一個屬性的類型,長度,映射字段等數據
namespace Alexander.Xbase.Interface
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class ParamAttribute:Attribute
{
private string _parameterType;
public string ParameterType
{
get { return _parameterType; }
set { _parameterType = value; }
}
private int _parameterLength;
public int ParameterLength
{
get { return _parameterLength; }
set { _parameterLength = value; }
}
private string _srccolumn;
public string Srccolumn
{
get { return _srccolumn; }
set { _srccolumn = value; }
}
public ParamAttribute(string ptype, int len)
{
_parameterType = ptype;
_parameterLength = len;
//throw new Exception("can not use");
}
public ParamAttribute(string ptype, int len,string src)
{
_parameterType = ptype;
_parameterLength = len;
_srccolumn = src;
//throw new Exception("can not use");
}
}
}使用的時候
定義一個實體類:
class tb
{
private string _aaa;
[Param("NChar",10)]
public string aaa
{
get { return _aaa; }
set { _aaa = value; }
}
private string _bbb;
[Param("NChar", 10)]
public string bbb
{
get { return _bbb; }
set { _bbb = value; }
}
}這樣子就把映射的類型,長度都存儲到特征里面。
To be continue 太累了,今晚休息了


浙公網安備 33010602011771號