开发者

Use in T4 some class from hosting project?

I have Linq to sql model inside a project on which .tt also added. T开发者_运维问答hat model I want to use in my T4 template. The question how to put a reference on it. If its a website and for console app too.


Let's see if I understand you correctly.

  1. You have a project with a Linq2Sql Model
  2. You want to add a .TT file to that project that uses the above model to generate something

If this is correct what I would do is load the .dbml file (it's xml) and generate the artifacts from that.

Something like this perhaps (a VS2010 template that generates some classes from DataClasses1.dbml):

<#@ template    language="C#" hostspecific="true"   #>
<#@ assembly    name="System.Core"                  #>
<#@ assembly    name="System.Xml"                   #>
<#@ assembly    name="System.Xml.Linq"              #>
<#@ import      nameSpace="System.Linq"             #>
<#@ import      nameSpace="System.Xml.Linq"         #>

namespace MyProgram
{
    using System.Data.Linq.Mapping;

<#
    const string ns             = "{http://schemas.microsoft.com/linqtosql/dbml/2007}";
    const string DatabaseName   = ns + "Database";
    const string TableName      = ns + "Table";
    const string TypeName       = ns + "Type";
    const string ColumnName     = ns + "Column";

    var xdoc = XDocument.Load (Host.ResolvePath ("DataClasses1.dbml"));
    var tables = xdoc.Elements (DatabaseName).Elements (TableName);

    foreach (var table in tables)
    {
        var types = table.Elements (TypeName);

        foreach (var @type in types)
        {
            var columns = @type.Elements (ColumnName);
#>
    [Table (Name = "<#=GetAttribute (@type, "Name")#>")]
    partial class <#=GetAttribute (@type, "Name")#>
    {
<#
            foreach (var column in columns)
            {
#>
        [Column (DbType = "<#=GetAttribute (column, "DbType")#>")]
        public <#=GetAttribute (column, "Type")#> <#=GetAttribute (column, "Name")#> { get; set; } 
<#
            }
#>
    }
<#
        }
    }
#>

}

<#+
    static string GetAttribute (XElement element, string name, string defaultValue = null)
    {
        if (defaultValue == null)
        {
            defaultValue = "<" + name + "_attribute_not_found>";
        }
        if (element == null)
        {
            return defaultValue;
        }

        var attribute = element.Attribute (name ?? "");
        if (attribute != null)
        {
            return attribute.Value ?? defaultValue;
        }
        else
        {
            return defaultValue;
        }
    }
#>


You should find this helpful:

http://www.olegsych.com/2008/02/t4-assembly-directive/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜