手把手教你写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  太累了,今晚休息了

posted on 2007-01-24 22:21  亚历山大同志  阅读(7854)  评论(5编辑  收藏  举报

导航