.Net Core 中使用PetaPoco ,T4生成模版

话不多说,直接上源码。

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
     {
        ///


        /// open the connection
        ///

        ///
        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 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 columns) { return repo.Update(this, columns); }
            public static int Update(string sql, params object[] args) { return repo.Update(sql, args); }
            public static int Update(Sql sql) { return repo.Update(sql); }
            public int Delete() { return repo.Delete(this); }
            public static int Delete(string sql, params object[] args) { return repo.Delete(sql, args); }
            public static int Delete(Sql sql) { return repo.Delete(sql); }
            public static int Delete(object primaryKey) { return repo.Delete(primaryKey); }
            public static bool Exists(object primaryKey) { return repo.Exists(primaryKey); }
            public static T SingleOrDefault(object primaryKey) { return repo.SingleOrDefault(primaryKey); }
            public static T SingleOrDefault(string sql, params object[] args) { return repo.SingleOrDefault(sql, args); }
            public static T SingleOrDefault(Sql sql) { return repo.SingleOrDefault(sql); }
            public static T FirstOrDefault(string sql, params object[] args) { return repo.FirstOrDefault(sql, args); }
            public static T FirstOrDefault(Sql sql) { return repo.FirstOrDefault(sql); }
            public static T Single(object primaryKey) { return repo.Single(primaryKey); }
            public static T Single(string sql, params object[] args) { return repo.Single(sql, args); }
            public static T Single(Sql sql) { return repo.Single(sql); }
            public static T First(string sql, params object[] args) { return repo.First(sql, args); }
            public static T First(Sql sql) { return repo.First(sql); }
            public static List Fetch(string sql, params object[] args) { return repo.Fetch(sql, args); }
            public static List Fetch(Sql sql) { return repo.Fetch(sql); }

            public static List Fetch(int page, int itemsPerPage, string sql, params object[] args) { return repo.Fetch(page, itemsPerPage, sql, args); }

            public static List SkipTake(int skip, int take, string sql, params object[] args) { return repo.SkipTake(skip, take, sql, args); }
            public static List SkipTake(int skip, int take, Sql sql) { return repo.SkipTake(skip, take, sql); }
            public static Page Page(int page, int itemsPerPage, string sql, params object[] args) { return repo.Page(page, itemsPerPage, sql, args); }
            public static Page Page(int page, int itemsPerPage, Sql sql) { return repo.Page(page, itemsPerPage, sql); }
            public static IEnumerable Query(string sql, params object[] args) { return repo.Query(sql, args); }
            public static IEnumerable Query(Sql sql) { return repo.Query(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 TableList = new List();

        public List Table = new List();

        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 Column = new List();

                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 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;
        ///


        /// open the connection
        ///

        ///
        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;
        } 

       

转载于:https://www.cnblogs.com/tonglei/p/6673997.html

你可能感兴趣的:(.Net Core 中使用PetaPoco ,T4生成模版)