代码改变世界

Linq to SQL T4 代码生成器 (二)访问设计器中的 Table 对象

2010-07-23 09:34  麦舒  阅读(2235)  评论(2编辑  收藏  举报

在上一篇文章中,介绍了如何访问 DataContext 对象,下面接着来讲解一下如何访问设计器中的表对象,并生成生体类代码。从 Northwind 数据库中拖一个表到设计器中。拖出来后,记得保存 dbml 文件,否则是无法访问到这个表的。 在这里拖的是 Catories 表,如下图所示:

 

 

我们可以通过访问 DataContext.Tables 来访拖放到设计器中的表。代码如下:

 

<# foreach(ITable table in DataContext.Tables){

}#
>

 

 

现在再来看看关于 ITable 的对象成员:

 

其中 Member 这个属性,指的是在 data context 实例中的成员名称,例如对于 Categories 表来说,这个 Member 就是 Categories。

 

Name 属性指的是该表的名称,而 Type 指就是该表的映射类。我们都知道,在 Linq to SQL 中,一个表可以映射成到一个类(或者多个继承类中),Type 属性就是用来访问这些映谢类。新建一个 DataClasses.tt 模版文件,复制下面的代码:

 

<#@ template inherits="ModelingTextTransformation" language="C#" debug="true" hostspecific="True"#>
<#@ QuickCode processor="DbmlProcessor" requires="ModelFile='Northwind.dbml'"#>
<#@ output extension=".cs" #>
<#@ import namespace = "System.Text.RegularExpressions" #>

using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace <#= DataContext.ContextNamespace #>
{
<# foreach(ITable table in DataContext.Tables){ #>
[Table(Name
="<#= table.Name #>")]
public class <#= table.Type.Name #>
{
}
<# } #>
}

 

按保存后生成的代码如下:

using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace DecodeDemo
{
[Table(Name
="dbo.Categories")]
public class Category
{
}
}

在这里可以看到,已经可以生成实体类了,当然,还有属性没有生成。(这个我们放在下一单文章中讲解)

现在来看一下如何生成继承类。从 ToolBox 工具栏中拖一个 DataClass 对象到调计器中,然后命名为 MyCatory,并继承于 Category。

通过访问 Type.SubTypes 成员来对于访问继承类。

 

代码: 

<# foreach(IType subType in table.Type.SubTypes){ #>
<#}#>

 

 

完整的模版代码如下:

<#@ template inherits="ModelingTextTransformation" language="C#" debug="true" hostspecific="True"#>
<#@ QuickCode processor="DbmlProcessor" requires="ModelFile='Northwind.dbml'"#>
<#@ output extension=".cs" #>
<#@ import namespace = "System.Text.RegularExpressions" #>

using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace <#= DataContext.ContextNamespace #>
{
<# foreach(ITable table in DataContext.Tables){ #>
[Table(Name
="<#= table.Name #>")]
public class <#= table.Type.Name #>
{
}
<# foreach(IType subType in table.Type.SubTypes){ #>
public class <#= subType.Name #>
{
}
<# } #>
<# } #>

}

 

 

 

生成的代码如下:

using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace DecodeDemo
{
[Table(Name
="dbo.Categories")]
public class Category
{
}

public class MyCategory
{
}
}

 

 

 

先讲到这里吧,下一篇再讲解属性的生成。

代码下载:https://files.cnblogs.com/ansiboy/ConsoleApplication2.zip