VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > C#编程 >
  • C#教程之C# ORM学习笔记:T4入门及生成数据库实体类(2)

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

/// <summary> /// 符号枚举 /// </summary> public enum Symbol { Normal = 1, Underline = 2 } #endregion #>
复制代码

    DBSchema.ttinclude主要实现了数据库工厂的功能。注:请将数据库连接字符串改成您自己的。

复制代码
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Data"#>
<#@ import namespace="System.IO"#>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating"#>

<#+
// T4 Template Block manager for handling multiple file outputs more easily.
// Copyright (c) Microsoft Corporation.All rights reserved.
// This source code is made available under the terms of the Microsoft Public License (MS-PL)

// Manager class records the various blocks so it can split them up
class Manager
{
    public struct Block
    {
        public string Name;
        public int Start, Length;
    }

    public List<Block> blocks = new List<Block>();
    public Block currentBlock;
    public Block footerBlock = new Block();
    public Block headerBlock = new Block();
    public ITextTemplatingEngineHost host;
    public ManagementStrategy strategy;
    public StringBuilder template;
    public string OutputPath { get; set; }

    public Manager(ITextTemplatingEngineHost host, StringBuilder template, bool commonHeader)
    {
        this.host = host;
        this.template = template;
        OutputPath = string.Empty;
        strategy = ManagementStrategy.Create(host);
    }

    public void StartBlock(string name)
    {
        currentBlock = new Block { Name = name, Start = template.Length };
    }

    public void StartFooter()
    {
        footerBlock.Start = template.Length;
    }

    public void EndFooter()
    {
        footerBlock.Length = template.Length - footerBlock.Start;
    }

    public void StartHeader()
    {
        headerBlock.Start = template.Length;
    }

    public void EndHeader()
    {
        headerBlock.Length = template.Length - headerBlock.Start;
    }    

    public void EndBlock()
    {
        currentBlock.Length = template.Length - currentBlock.Start;
        blocks.Add(currentBlock);
    }

    public void Process(bool split)
    {
        string header = template.ToString(headerBlock.Start, headerBlock.Length);
        string footer = template.ToString(footerBlock.Start, footerBlock.Length);
        blocks.Reverse();
        foreach(Block block in blocks) {
            string fileName = Path.Combine(OutputPath, block.Name);
            if (split) {
                string content = header + template.ToString(block.Start, block.Length) + footer;
                strategy.CreateFile(fileName, content);
                template.Remove(block.Start, block.Length);
            } else {
                strategy.DeleteFile(fileName);
            }
        }
    }
}

class ManagementStrategy
{
    internal static ManagementStrategy Create(ITextTemplatingEngineHost host)
    {
        return (host is IServiceProvider) ? new VSManagementStrategy(host) : new ManagementStrategy(host);
    }

    internal ManagementStrategy(ITextTemplatingEngineHost host) { }

    internal virtual void CreateFile(string fileName, string content)
    {
        File.WriteAllText(fileName, content);
    }

    internal virtual void DeleteFile(string fileName)
    {
        if (File.Exists(fileName))
            File.Delete(fileName);
    }
}

class VSManagementStrategy : ManagementStrategy
{
    private EnvDTE.ProjectItem templateProjectItem;

    internal VSManagementStrategy(ITextTemplatingEngineHost host) : base(host)
    {
        IServiceProvider hostServiceProvider = (IServiceProvider)host;
        if (hostServiceProvider == null)
            throw new ArgumentNullException("Could not obtain hostServiceProvider");

        EnvDTE.DTE dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE));
        if (dte == null)
            throw new ArgumentNullException("Could not obtain DTE from host");

        templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile);
    }

    internal override void CreateFile(string fileName, string content)
    {
        base.CreateFile(fileName, content);
        ((EventHandler)delegate { templateProjectItem.ProjectItems.AddFromFile(fileName); }).BeginInvoke(null, null, null, null);
    }

    internal override void DeleteFile(string fileName)
    {
        ((EventHandler)delegate { FindAndDeleteFile(fileName); }).BeginInvoke(null, null, null, null);
    }

    private void FindAndDeleteFile(string fileName)
    {
        foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems)
        {
            if (projectItem.get_FileNames(0) == fileName)
            {
                projectItem.Delete();
                return;
            }
        }
    }
}
#>
复制代码

    MultiDocument.ttinclude主要实现了多文档的功能。

    5.2、添加一个MultModelAuto.tt文本模板,代码如下:

复制代码
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#@ include file="T4Code/DBSchema.ttinclude"#>
<#@ include file="T4Code/MultiDocument.ttinclude"#>
<# var manager = new Manager(Host, GenerationEnvironment, true) { OutputPath = Path.GetDirectoryName(Host.TemplateFile)}; #>
<#
    //System.Diagnostics.Debugger.Launch();//调试
    var dbSchema = DBSchemaFactory.GetDBSchema();
    List<string> tableList = dbSchema.GetTableList();
    foreach(string tableName in tableList)
    {
        manager.StartBlock(tableName+".cs");
        Table table = dbSchema.GetTableMetadata(tableName);
#>
//-------------------------------------------------------------------------------
// 此代码由T4模板MultModelAuto自动生成
// 生成时间 <#=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")#>
// 对此文件的更改可能会导致不正确的行为,并且如果重新生成代码,这些更改将会丢失。

//-------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;

namespace Project.Model
{
    [Serializable]
    public class <#=tableName#>
    {
        #region Constructor
        public <#=tableName#>() { }

        public <#=tableName#>(<#=table.DataTypes#>)
        {
<#
        foreach(Column c in table.Columns)
        {
#>
            this.<#=c.UpperColumnName#> = <#=c.UpperColumnName#>;
<#
        }
#>
        }
        #endregion

        #region Attributes
<#
        foreach(Column c in table.Columns)
        {
#>
        public <#=GeneratorHelper.GetQuestionMarkByType(c.DataType)#> <#=c.UpperColumnName#> {get; set;}
<#
        }
#>
        #endregion

        #region Validator
        public List<string> ErrorList = new List<string>();
        private bool Validator()
        {    
            bool validatorResult = true;
<#
            foreach(Column c in table.Columns)
            {
                if (!c.AllowDBNull)
                {
                    if(c.DataType == GeneratorHelper.StringType)
                    {
#>
            if (string.IsNullOrEmpty(<#=c.UpperColumnName#>))
            {
                validatorResult = false;
                ErrorList.Add("The <#=c.UpperColumnName#> should not be empty.");
            }
<#
                    }

                    if(c.DataType == GeneratorHelper.DateTimeType)
                    {
#>
            if (<#=c.UpperColumnName#> == null)
            {
                validatorResult = false;
                ErrorList.Add("The <#=c.UpperColumnName#> should not be empty.");
            }
<#
                    }
                }

            if (c.DataType == GeneratorHelper.StringType)
            {
#>
            if (<#=c.UpperColumnName#> != null && <#=c.UpperColumnName#>.Length > <#=c.MaxLength#>)
            {
                validatorResult = false;
                ErrorList.Add("The length of <#=c.UpperColumnName#> should not be greater then <#=c.MaxLength#>.");
            }
<#
            }
            }
#>
            return validatorResult;
        }    
        #endregion
    }
}
<#
        manager.EndBlock();
    }
    dbSchema.Dispose();
    manager.Process(true);
#>
复制代码

    代码保存后,可以看到此文件下面已按数据表生成了多个实体类文件:

 

    参考自:

    https://www.cnblogs.com/dataadapter/p/3844394.html

    https://www.cnblogs.com/yank/archive/2012/02/14/2342287.html

相关教程
        
关于我们--广告服务--免责声明--本站帮助-友情链接--版权声明--联系我们       黑ICP备07002182号