A Data Access Layer to persist business objects using attributes and reflection - Part II [无常译]
2006-04-10 21:47 无常 阅读(734) 评论(0) 编辑 收藏 举报A Data Access Layer to persist business objects using attributes and reflection - Part II
By xicoloko
Persistance to business objects through attributes and reflection
[无常译]
下载源代码 - 3.4 Kb
目录:
第一部分
第二部分
第三部分
前言
上一篇文章中我已经介绍了用特性来声明business object的方法。在这篇文章中,我将要介绍怎样从类中提取这些声明信息。解释怎么在一个应用程序来根据使用在类的特性来生成创建数据表的SQL脚本。
工具
这是一个控制台程序。在参数中传递一个程序集的名字。这个工具就载入程序集,枚举出所有使用DataTable特性标记过的类,并且生成创建数据表的SQL脚本。
我们从载入程序集的代码开始。
{
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属性声明的类。下面的代码来完成这个任务。
{
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());
}
}
}
}
上面的代码从程序集中取出所有的类型,然后再判断是否是一个类,并且这拥有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种条件的脚本:主键是int、自动增长类型;属性类型是string,int,decimal和DataTime。
源代码中包含以下的程序集:
- DAL.dll: 包含特性类
- Customer.dll: 包含business objects
- scriptGen.exe: 生成SQL脚本的工具
后续内容
下一篇文章在,我将要创建一个完整的DAL,在运行时获得对象并在一个数据库中将其持久化。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架