话不多说,直接上源码。
1.引用NuGet
2.添加T4
<#@ template debug="true" hostspecific="false" language="C#" #>
<#@ 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.Common" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ output extension=".cs" #>
<#
string Namespace="添加命名空间";
string RepoName="添加类名";
string ConnectionStr="添加连接串";
var builder = new T4Builder("Data Source=添加数据库连接");
#>
using PetaPoco.NetCore;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace <#=Namespace #>
{
public partial class <#=RepoName #> : Database
{
/// <summary>
/// open the connection
/// </summary>
/// <returns></returns>
private static SqlConnection OpenConnection()
{
SqlConnection conn = new SqlConnection("添加连接串");
conn.Open();
return conn;
}
private static SqlConnection OpenConnection(string name)
{
SqlConnection conn = new SqlConnection(JsonConfig.JsonRead(name));
conn.Open();
return conn;
}
public <#=RepoName#>() : base(OpenConnection())
{
CommonConstruct();
}
public <#=RepoName#>(string connectionStringName) : base(OpenConnection(connectionStringName))
{
CommonConstruct();
}
partial void CommonConstruct();
public interface IFactory
{
<#=RepoName #> GetInstance();
}
public static IFactory Factory { get; set; }
public static <#=RepoName #> GetInstance()
{
if (_instance != null)
return _instance;
if (Factory != null)
return Factory.GetInstance();
else
return new <#=RepoName #>();
}
[ThreadStatic] static <#=RepoName #> _instance;
public override void OnBeginTransaction()
{
if (_instance == null)
_instance = this;
}
public override void OnEndTransaction()
{
if (_instance == this)
_instance = null;
}
public class Record<T> where T : new()
{
public static <#=RepoName #> repo { get { return <#=RepoName #>.GetInstance(); } }
public bool IsNew() { return repo.IsNew(this); }
public object Insert() { return repo.Insert(this); }
public void Save() { repo.Save(this); }
public int Update() { return repo.Update(this); }
public int Update(IEnumerable<string> columns) { return repo.Update(this, columns); }
public static int Update(string sql, params object[] args) { return repo.Update<T>(sql, args); }
public static int Update(Sql sql) { return repo.Update<T>(sql); }
public int Delete() { return repo.Delete(this); }
public static int Delete(string sql, params object[] args) { return repo.Delete<T>(sql, args); }
public static int Delete(Sql sql) { return repo.Delete<T>(sql); }
public static int Delete(object primaryKey) { return repo.Delete<T>(primaryKey); }
public static bool Exists(object primaryKey) { return repo.Exists<T>(primaryKey); }
public static T SingleOrDefault(object primaryKey) { return repo.SingleOrDefault<T>(primaryKey); }
public static T SingleOrDefault(string sql, params object[] args) { return repo.SingleOrDefault<T>(sql, args); }
public static T SingleOrDefault(Sql sql) { return repo.SingleOrDefault<T>(sql); }
public static T FirstOrDefault(string sql, params object[] args) { return repo.FirstOrDefault<T>(sql, args); }
public static T FirstOrDefault(Sql sql) { return repo.FirstOrDefault<T>(sql); }
public static T Single(object primaryKey) { return repo.Single<T>(primaryKey); }
public static T Single(string sql, params object[] args) { return repo.Single<T>(sql, args); }
public static T Single(Sql sql) { return repo.Single<T>(sql); }
public static T First(string sql, params object[] args) { return repo.First<T>(sql, args); }
public static T First(Sql sql) { return repo.First<T>(sql); }
public static List<T> Fetch(string sql, params object[] args) { return repo.Fetch<T>(sql, args); }
public static List<T> Fetch(Sql sql) { return repo.Fetch<T>(sql); }
public static List<T> Fetch(int page, int itemsPerPage, string sql, params object[] args) { return repo.Fetch<T>(page, itemsPerPage, sql, args); }
public static List<T> SkipTake(int skip, int take, string sql, params object[] args) { return repo.SkipTake<T>(skip, take, sql, args); }
public static List<T> SkipTake(int skip, int take, Sql sql) { return repo.SkipTake<T>(skip, take, sql); }
public static Page<T> Page(int page, int itemsPerPage, string sql, params object[] args) { return repo.Page<T>(page, itemsPerPage, sql, args); }
public static Page<T> Page(int page, int itemsPerPage, Sql sql) { return repo.Page<T>(page, itemsPerPage, sql); }
public static IEnumerable<T> Query(string sql, params object[] args) { return repo.Query<T>(sql, args); }
public static IEnumerable<T> Query(Sql sql) { return repo.Query<T>(sql); }
}
}
<#
foreach(var item in builder.Table)
{
#>
[TableName("<#=item.TableName#>")]
<#
if(!String.IsNullOrWhiteSpace(item.Primkey))
{
#>
[PrimaryKey("<#=item.Primkey #>")]
<#
}
#>
[ExplicitColumns]
public partial class <#=item.TableNameStr#>:<#=RepoName#>.Record<<#=item.TableNameStr#>>
{
<#
foreach(var col in item.Column)
{
#>
[Column] public <#=col.ColumnType#> <#=col.ColumnName#> {get;set;}
<#
}
#>
}
<#
}
#>
}
<#+
public class T4Builder
{
public List<String> TableList = new List<String>();
public List<TableFrame> Table = new List<TableFrame>();
public T4Builder(string conectionstring)
{
SqlConnection con = new SqlConnection(conectionstring);
con.Open();
SqlCommand cmd = new SqlCommand("select name from sysobjects where xtype='u'", con);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var tablename = reader.GetValue(0).ToString();
TableList.Add(tablename);
}
foreach (var tablename in TableList)
{
var TableFrame = new TableFrame();
TableFrame.TableName = "dbo." + tablename;
#region 获取主键
SqlCommand cmd_prikey = new SqlCommand("EXEC sp_pkeys @table_name='" + tablename + "' ", con);
var key_result = cmd_prikey.ExecuteReader();
while (key_result.Read())
{
TableFrame.Primkey = key_result.GetValue(3) != null ? key_result.GetValue(3).ToString() : null;
}
#endregion
#region 获取列名
SqlCommand cmd_table = new SqlCommand("select COLUMN_NAME,DATA_TYPE,NUMERIC_SCALE,IS_NULLABLE from information_schema.columns where TABLE_NAME='" + tablename + "'", con);
var table_result = cmd_table.ExecuteReader();
List<Colum> Column = new List<Colum>();
while (table_result.Read())
{
Colum Columindex = new Colum();
Columindex.ColumnName = table_result.GetValue(0) != null ? table_result.GetValue(0).ToString() : null;
if (!String.IsNullOrEmpty(Columindex.ColumnName))
{
var ColumTypeStr = GetPropertyType(table_result.GetValue(1) != null ? table_result.GetValue(1).ToString() : null, table_result.GetValue(2) != null ? table_result.GetValue(2).ToString() : null);
if (table_result.GetValue(3).ToString() == "YES" && ColumTypeStr != "string" && ColumTypeStr != "Guid")
{
ColumTypeStr = ColumTypeStr + "?";
}
Columindex.ColumnType = ColumTypeStr;
Column.Add(Columindex);
}
}
#endregion
TableFrame.Column = Column;
Table.Add(TableFrame);
}
con.Close();
con.Dispose();
}
private string GetPropertyType(string sqlType, string dataScale)
{
string sysType = "string";
sqlType = sqlType.ToLower();
switch (sqlType)
{
case "bigint":
sysType = "long";
break;
case "smallint":
sysType = "short";
break;
case "int":
sysType = "int";
break;
case "uniqueidentifier":
sysType = "Guid";
break;
case "smalldatetime":
case "datetime":
case "date":
sysType = "DateTime";
break;
case "float":
sysType = "double";
break;
case "real":
case "numeric":
case "smallmoney":
case "decimal":
case "money":
case "number":
sysType = "decimal";
break;
case "tinyint":
sysType = "byte";
break;
case "bit":
sysType = "bool";
break;
case "image":
case "binary":
case "varbinary":
case "timestamp":
sysType = "byte[]";
break;
}
if (sqlType == "number" && dataScale == "0")
return "long";
return sysType;
}
}
public class TableFrame
{
public string TableName { get; set; }
public string Primkey { get; set; }
public List<Colum> Column { get; set; }
public string TableNameStr
{
get
{
return TableName != null ? TableName.Replace("dbo.", "").Trim() : null;
}
}
}
public class Colum
{
public string ColumnName { get; set; }
public string ColumnType { get; set; }
}
#>
好到这T4模版在Core中生成 PatePoco模版已经结束了。这个也是一个简单的版本,希望大家有个参考随时沟通使用中的问题。
突然发现了一个小坑,每次conn都实例化一次,改进了下。
private static SqlConnection con;
/// <summary>
/// open the connection
/// </summary>
/// <returns></returns>
private static SqlConnection OpenConnection()
{
if (con == null)
{
con = new SqlConnection(JsonConfig.JsonRead("CGTSettings", "cgtTravelConnection"));
}
else
{
if (con.State == System.Data.ConnectionState.Closed)
con.Open();
}
return con;
}
private static SqlConnection OpenConnection(string name)
{
if (con == null)
{
con = new SqlConnection(JsonConfig.JsonRead(name));
}
else
{
if (con.State == System.Data.ConnectionState.Closed)
con.Open();
}
return con;
}