【问题标题】:Convert T4 Template to connect to MySQL database?转换 T4 模板以连接到 MySQL 数据库?
【发布时间】:2015-03-06 15:47:33
【问题描述】:

我在http://www.haneycodes.net/automatically-generate-pocos-from-db-with-t4/ 找到了以下T4 Template,它连接到SqlServer database and generates POCO classes from the tables。我想对MySql 做同样的事情,但我不确定我需要改变什么。我尝试只连接一个 MySqlConnection,但这没有用。我必须创建一个 MySql Server 实例吗?如果有人知道使用 MySQL 创建 POCO 的替代方法,我也对此持开放态度。

<#@ template language="C#" hostspecific="true" debug="True" #> 
<#@ assembly name="System.Core" #> <#@ assembly name="System.Data" #> 
<#@ assembly name="System.Xml" #> 
<#@ assembly name="Microsoft.SqlServer.Smo" #>
 <#@ assembly name="Microsoft.SqlServer.ConnectionInfo" #> 
 <#@ assembly name="Microsoft.SqlServer.Management.Sdk.Sfc" #> 
 <#@ import namespace="System" #> 
 <#@ import namespace="System.IO" #> 
 <#@ import namespace="System.Linq" #> 
 <#@ import namespace="System.Text" #> 
 <#@ import namespace="Microsoft.SqlServer.Management.Smo" #> 
 <#    

string sqlServer = "9.9.9.9";     
string sqlLogin = "admin";     
string sqlPassword = "password";     
string sqlDatabase = "MyDatabase";     
string classNamespace = "Your.Namespace.Here";     
string destinationFolder = "PocoFolder";       


Server server = new Server(sqlServer);     
server.ConnectionContext.LoginSecure = false;     
server.ConnectionContext.Login = sqlLogin;    
server.ConnectionContext.Password = sqlPassword;     
server.ConnectionContext.Connect();       

foreach (Table table in server.Databases[sqlDatabase].Tables)    
{        

     if (table.Name.StartsWith("sys"))         
     {             
         continue;         

     } #> 

     using System;  

     namespace <#= classNamespace #> 
     {     

     public class <#= table.Name #>      
     { <#          
             int columnCount = table.Columns.Count;        
      int i = 0;                   
     foreach (Column col in table.Columns)        
      {             
          i++;             
          string propertyType = GetNetDataType(col.DataType.Name);               
          // If we can't map it, skip it             
          if (string.IsNullOrWhiteSpace(propertyType))             
          {                 
              // Skip                 
              continue;             
          }               
          // Handle nullable columns by making the type nullable             
          if (col.Nullable && propertyType != "string")             
          {                
               propertyType += "?";             
          } #>         
          public <#= propertyType #> <#= col.Name #> { get; set; } <#            
           // Do we insert the space?            
           if (i != columnCount)             
           { #> <#             
           } #> <#         
      } #>     
      } 
      }       
      <#         
      // Write new POCO class to its own file         
      SaveOutput(table.Name + ".cs", destinationFolder);     
}  #> 
<#+     
public static string GetNetDataType(string sqlDataTypeName)     
{         switch (sqlDataTypeName.ToLower())         
    {             
    case "bigint":                
         return "Int64";             
    case "binary":             
    case "image":             
    case "varbinary":                 
        return "byte[]";             
    case "bit":                 
        return "bool";             
    case "char":                 
        return "char";             
    case "datetime":             
    case "smalldatetime":                 
        return "DateTime";             
    case "decimal":             
    case "money":             
    case "numeric":                 
        return "decimal";             
    case "float":                 
        return "double";             
    case "int":                 
        return "int";             
    case "nchar":             
    case "nvarchar":             
    case "text":             
    case "varchar":             
    case "xml":                 
        return "string";             
    case "real":                
         return "single";          
       case "smallint":             
            return "Int16";         
        case "tinyint":             
            return "byte";          
       case "uniqueidentifier":     
                    return "Guid";  
                                 default:              
           return null;         
    }     
}       

void SaveOutput(string outputFileName, string destinationFolder)   
  {         
      // Write to destination folder       
        string templateDirectory = Path.Combine(Path.GetDirectoryName(Host.TemplateFile), destinationFolder);         string outputFilePath = Path.Combine(templateDirectory, outputFileName);        
       File.Delete(outputFilePath);      
         File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString());          
        // Flush generation         
      this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);    
   } #> 

【问题讨论】:

  • 当你有 EF 时,为什么还要经历所有的麻烦?
  • @DionV。 - 我不能使用 EF。我将使用Dapper,但我不想手动编码所有 POCO 文件。
  • @DionV。 - 很棒的评论。这真的很有帮助。

标签: c# mysql poco t4


【解决方案1】:

我在我的 VS 扩展 (T4 Awesome) 中使用了 db schema reader project 来访问数据库结构。它支持任何 ADO 提供程序。您可以下载 MySql 提供程序here。 db schema reader 项目上的文档非常好,因此您应该能够使用它们来弄清楚如何连接到数据库并读取结构。

正如我所说,我在我的扩展中实现了这一点,所以如果你想要一个快速的解决方案,你可以download it 试试看。如果没有,您几乎可以按照您已有的方式执行此操作,但引用 db 模式阅读器项目名称空间和程序集。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    相关资源
    最近更新 更多