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

上一篇文章给大家介绍了Linq to SQL 设计器中 Table 对象的访问,本文主要介绍一下 Linq to SQL 设计器中 Column 对象的访问,要生成实体类的属性,必须通过访问 Column 对象。下面来看代码:

<#@ 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(IColumn column in table.Type.Columns){#>
[Column(Name
="<#= column.Name #>", UpdateCheck="<#= column.UpdateCheck #>")]
public <#= column.Type #> <#= column.Member #>
{
get;
set;
}
<#} #>
}
<# } #>

}

生成代码如下:

代码

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

namespace DecodeDemo
{
[Table(Name
="dbo.Categories")]
public class Category
{
[Column(Name
="CategoryID", UpdateCheck="Never")]
public System.Int32 CategoryID
{
get;
set;
}
[Column(Name
="CategoryName", UpdateCheck="Never")]
public System.String CategoryName
{
get;
set;
}
[Column(Name
="Description", UpdateCheck="Never")]
public System.String Description
{
get;
set;
}
[Column(Name
="Picture", UpdateCheck="Never")]
public System.Data.Linq.Binary Picture
{
get;
set;
}
}

}

我们要注意的是这一句:

<# foreach(IColumn column in table.Type.Columns){#>

很多朋友可能会有疑问,怎么 Columns 放在 Type 对象里,而不是 table 对象中呢?可能这样理解,在 Linq to SQL 设计器中,具有继承关系的多个类,都城是映射到同一个表的。也就是说,一个表 (ITable) 可以对应多个类 (IType),而每个类,都包含有一个或都多个列(IColumn)。也就是说,你通过 IType.Columns 访问到的列,不是表所包含的全部列,而只是一部份映到类属性的列(如果该类没有继承类则为全部)。

IColumn 的成员如下图所示,这些成员名称,使用过 Linq to SQL 的朋友都熟悉了,因此也不打算解释了。如果有任何疑问,请给我留言。完整的属性列表请点击:

http://www.alinq.org/document/decode.htm

完整代码以及示例请到本系列的第一篇文章那里下载:http://www.cnblogs.com/ansiboy/archive/2010/07/22/1782982.html

原文地址:https://www.cnblogs.com/ansiboy/p/1784293.html