生成效果
模板代码
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Data"#>
<#@ import namespace="System.Data.SqlClient"#>
<#// 连接字符串
string connectionString = "Server=DESKTOP-7IR5JSN;Database=BlazorApp;Integrated Security=False;User ID=sa;Password=asdf-1234;";// 数据库连接
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();// 查询数据库中的表信息
string query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
SqlCommand command = new SqlCommand(query, connection);
List<string> tables = new List<string>();using (SqlDataReader reader = command.ExecuteReader())
{while (reader.Read()){tables.Add(reader.GetString(0));}
}// 生成模型类
foreach (var table in tables)
{
#>
namespace BlazorORM.Entity
{using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using SqlSugar;// 生成的模型类对应数据库表: <#= table #>[SugarTable("<#= table #>")]public class <#= table #>{
<#query = $"SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{table}'";command.CommandText = query;List<string> columns = new List<string>();using (SqlDataReader reader = command.ExecuteReader()){while (reader.Read()){string columnName = reader.GetString(0);string columnType = reader.GetString(1);
#>// 对应数据库列:<#= columnName #>,类型:<#= columnType #>[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] // 可根据需要设置主键、自增等属性public <#= GetCSharpType(columnType) #> <#= columnName #> { get; set; }
<#}}
#>}
}
<#
}// 关闭连接
connection.Close();// 将数据库类型映射为 C# 类型
string GetCSharpType(string dbType)
{// 可根据数据库类型自定义映射switch (dbType){case "int":return "int";case "nvarchar":return "string";// 添加其他数据库类型映射default:return "object";}
}
#>