欢迎光临
我们一直在努力

使用属性和反射过渡从数据存取层到业务物件 – II-.NET教程,数据库应用

建站超值云服务器,限时71元/月

简介

前面的文章我介绍了使用attributes来描述业务物件.这篇文章我将会展示如何从类中提取描述信息.为了解释它是如何工作的,我将通过前面在类中使用的attributes写个应用来创建sql脚本用来生成表.

工具

这是一个控制台应用.工具将会装载装配件,列举出类中标有datatable的attibute生成sql脚本用来创建表.

开始装载部分代码:

public static void main(string[] args)

{

if (args.length != 1)

{

console.writeline("usage: scriptgen [assembly path]");

return;

}

assembly assembly = null;

try

{

assembly = assembly.loadfrom(args[0]);

}

catch (exception e)

{

console.writeline("failed to load assembly [" + args[0] + "]");

console.writeline(e.message);

}

}

以上的代码试图通过参数路径来装载装配件.现在我们必须列举出所有的含有datatable attribute的装配件.为了完成这个工作,请看如下代码:

public void parseassembly(assembly assembly)

{

type[] types = assembly.gettypes();

foreach(type type in types)

{

if (type.isclass)

{

datatableattribute[] datatable = (datatableattribute[])

type.getcustomattributes(typeof(datatableattribute),

true);

if (datatable.length > 0)

{

console.writeline("found class {0}", type.tostring());

}

}

}

}

以下是列举属性的代码.

void parseclass(type type, datatableattribute datatable)

{

propertyinfo[] properties = type.getproperties();

// gets the key field

foreach (propertyinfo property in properties)

{

keyfieldattribute[] key = (keyfieldattribute[])

property.getcustomattributes(typeof(keyfieldattribute),

true);

if (key.length > 0)

{

console.writeline("key = " + property.name + " type is "

+ property.propertytype);

break;

}

}

// gets the other fields

foreach (propertyinfo property in properties)

{

basefieldattribute[] field = (basefieldattribute[])

property.getcustomattributes(typeof(basefieldattribute),

true);

if (field.length > 0)

{

if (!(field[0] is keyfieldattribute))

{

console.writeline("property " + property.name

+ " [" + property.propertytype + "] " +

+ "maps to column [

+ field[0].columnname + "]");

}

}

}

}

现在我们不得不创建sql脚本.我们的工具仅能满足2个需求: key是int,identify 属性类型只有这些是允许的:string,int,decimal,和datetime.

源文件将会创建以下的装配件:

dal.dll: 包含 attributes

customer.dll: 包含业务物件

scriptgen.exe: 用来生成sql脚本的工具.

下一步

接下来的文章我将创建整个dal,用来在运行时间得到物件等等.

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 使用属性和反射过渡从数据存取层到业务物件 – II-.NET教程,数据库应用
分享到: 更多 (0)

相关推荐

  • 暂无文章