ORM中資料模型產生利器T4 Templates

來源:互聯網
上載者:User
Supported databases¶

Database Template
MS SQL MSSQL.ttinclude
MySql MySql.ttinclude
PostgreSQL PostgreSQL.ttinclude
Sybase Sybase.ttinclude

Setup¶

To generate a data model from your database follow the steps below:

  • Copy T4 templates from the BLToolkit/Source/Templates folder to your project.
  • Add new .tt file into your project.
  • Change the file in following way:

 

<#@ template language="C#v3.5"         #><#@ output extension=".generated.cs"   #><#@ include file="BLToolkit.ttinclude" #><#@ include file="Sybase.ttinclude"    #><#    ConnectionString     = "Data Source=DBHost;Port=5000;Database=BLToolkitData;Uid=sa";    DataProviderAssembly = @"....../Sybase.AdoNet2.AseClient.dll";

Namespace = "Templates"; DataContextName = "DataModel";

GenerateModel();#>

The ConnectionString variable defines connection to your database. DataProviderAssembly specifies the path to data provider assembly. If the assembly is installed in GAC, try the following directive instead:

<#@ assembly name="Sybase.AdoNet2.AseClient" #>

It is not required for MS SQL data provider, so the template for MS SQL can be as demonstrated below:

<#@ template language="C#v3.5"         #><#@ output extension=".generated.cs"   #><#@ include file="BLToolkit.ttinclude" #><#@ include file="MSSQL.ttinclude"     #><#    ConnectionString = "Server=.;Database=BLToolkitData;Integrated Security=SSPI";

Namespace = "Templates"; DataContextName = "DataModel";

GenerateModel();#>

The Namespace and DataContextName variables specify namespace and DataContext class name. Unfortunately, T4 does not have a simple way to get Visual Studio settings. However as an alternative you can install T4 Toolbox and change the template in the following way:

<#@ template language="C#v3.5" hostspecific="True" #><#@ output extension=".generated.cs"     #><#@ include file="BLToolkit.ttinclude"   #><#@ include file="BLT4Toolkit.ttinclude" #><#@ include file="MSSQL.ttinclude"       #><#    ConnectionString = "Server=.;Database=BLToolkitData;Integrated Security=SSPI";

GenerateModel();#>

Now, these parameters will be taken from your project. Note, T4 Toolbox must be installed on your computer and this way works under Visual Studio only.

VB Support¶

The following example demonstrates how to generate VB code:

<#@ template language="C#v3.5"         #><#@ output extension=".generated.vb"   #><#@ include file="BLToolkit.ttinclude" #><#@ include file="MSSQL.ttinclude"     #><#@ include file="VB.ttinclude"        #><#    ConnectionString = "Server=.;Database=BLToolkitData;Integrated Security=SSPI";

Namespace = "Templates"; DataContextName = "DataModel";

GenerateModel();#>

Customization¶

The following variables can be used to customize generating code:

string DatabaseName             = null;string DataContextName          = "DataContext";string Namespace                = "DataModel";string BaseDataContextClass     = "DbManager";string BaseEntityClass          = null;string OneToManyAssociationType = "IEnumerable<{0}>";bool   RenderField              = false;

The generating process consists of two steps: metadata loading and model rendering. You can modify metadata after it's loaded. The following code provides a few examples:

<#@ template language="C#v3.5"         #><#@ output extension=".generated.cs"   #><#@ include file="BLToolkit.ttinclude" #><#@ include file="MSSQL.ttinclude"     #><#    ConnectionString = "Server=.;Database=BLToolkitData;Integrated Security=SSPI";

Namespace = "Templates"; DataContextName = "DataModel";

// This method has to be called before any metadata change. // LoadMetadata();

// Change the BinaryDataID field name of the BinaryData table to "ID". // Tables["BinaryData"].Columns["BinaryDataID"].MemberName = "ID";

// Change the FK_Employees_Employees association name of the Employees table to "ReportsToEmployee". // Tables["Employees"].ForeignKeys["FK_Employees_Employees"].MemberName = "ReportsToEmployee";

// Change a field name to "ID" if the field is a primary key and its name is ClassNameID. // foreach (var t in Tables.Values) foreach (var c in t.Columns.Values) if (c.IsPrimaryKey && t.TableName + "ID" == c.ColumnName) c.MemberName = "ID";

// Add inheritance to entity classes from EntityBase<T>. // Usings.Add("BLToolkit.Common");

foreach (var t in Tables.Values) t.BaseClassName = "EntityBase<" + t.ClassName + ">";

GenerateModel();#>

The template has some basic logic to resolve nonstandard field names, association types and names. If this logic fails, you can make any changes yourself.

The metadata structure looks as the following:

Dictionary<string,Table> Tables = new Dictionary<string,Table>();

partial class Table{ public string Owner; public string TableName; public string ClassName; public string BaseClassName; public string DataContextPropertyName; public bool IsView; public List<string> Attributes;

public Dictionary<string,Column> Columns; public Dictionary<string,ForeignKey> ForeignKeys;}

partial class Column{ public int ID; public string ColumnName; public string MemberName; public bool IsNullable; public bool IsIdentity; public string Type; public bool IsClass; public DbType DbType; public SqlDbType SqlDbType; public int PKIndex = -1; public List<string> Attributes = new List<string>(); public bool IsPrimaryKey;}

enum AssociationType{ Auto, OneToOne, OneToMany, ManyToOne,}

partial class ForeignKey{ public string KeyName; public string MemberName; public Table OtherTable; public List<Column> ThisColumns; public List<Column> OtherColumns; public bool CanBeNull; public ForeignKey BackReference; public AssociationType AssociationType;}

WCF Support¶

The following include allows generating WCF attributes.

<#@ template language="C#v3.5"         #><#@ output extension=".generated.cs"   #><#@ include file="BLToolkit.ttinclude" #><#@ include file="WCFAttributes.ttinclude" #><#@ include file="MSSQL.ttinclude"     #><#    ConnectionString = "Server=.;Database=BLToolkitData;Integrated Security=SSPI";    GenerateModel();#>

Pluralize / Singularize Table Names¶
<#@ template language="C#v3.5"         #><#@ output extension=".generated.cs"   #><#@ include file="BLToolkit.ttinclude" #><#@ include file="MSSQL.ttinclude"     #><#@ include file="PluralSingular.ttinclude" #><#    ConnectionString = "Server=.;Database=BLToolkitData;Integrated Security=SSPI";

//PluralizeClassNames = true; SingularizeClassNames = true;

PluralizeDataContextPropertyNames = true; //SingularizeDataContextPropertyNames = true;

GenerateModel();#>
http://www.bltoolkit.net/Doc.T4Templates.ashx
http://msdn.microsoft.com/en-us/library/bb126445.aspxs

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.