当前位置:网站首页>.Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)

.Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)

2022-04-23 17:11:00 Tomato Warrior

Catalog

Preface

One 、RazorEngine.NetCore   Basic use

1. install Nuget package  

2. The official sample

Two 、 The core idea

1. Basic configuration

2. Template reading

3. Acquisition of database related information

4. The main methods of generating entity files

5. Auxiliary method of template file

6. Template file

3、 ... and 、 Effect display

summary


Preface

We will implement an entity class generator with basic functions

Basic goal : Customizable template 、 Configurable database links 、 Configurable template

development environment :mysql5.7.31、vs2019 、.net core3.1  Dapper  MVC project

The source code of the project is at the end of the article


One 、RazorEngine.NetCore   Basic use

1. install Nuget package  

RazorEngine.NetCore 3.1.0

2. The official sample

using RazorEngine;
using RazorEngine.Templating; // For extension methods.

string template = "Hello @Model.Name, welcome to RazorEngine!";
var result = Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });

Official project address :https://github.com/fouadmess/RazorEngine

As can be seen from the above example , Template and anonymous entity can be combined through two simple sentences of code , Generate the text we want

Next, I will gradually improve it on this basis .


Two 、 The core idea

1. Basic configuration

The selection of template and database link need to be configured :appsettings.json

  "DbConfigInfo": {
    "TemplateName": "modelTest.cshtml", // The name of the currently used template file 
    "ConnList": [  // Database link configuration ,InUse  Indicates the currently used link 
      {
        "ConnStr": "Database=xlcloud;Data Source=172.172.3.50;Port=3306;User Id=user;Password=123456;Charset=utf8;",
        "InUse": true
      },
      {
        "ConnStr": "Database=jscloud;Data Source=172.172.3.56;Port=3306;User Id=user;Password=pwd;Charset=utf8;",
        "InUse": false
      }
    ]
  }

2. Template reading

The template should be read from the local file , And it should be compiled when the program starts , Because the template compilation will take a long time ( Maybe a few seconds )

            // Register template middleware 
            app.Use(async (context, next) =>
            {
                var templateName = Configuration.GetSection("DbConfigInfo")["TemplateName"];
                var filePath = Path.Combine(env.WebRootPath, "templates", templateName);

                if (!File.Exists(filePath))
                {
                    await context.Response.WriteAsync(" The template file does not exist ");
                }
                else {

                    // Open and read the template 
                    string template = File.ReadAllText(filePath);
                    // Add the template 
                    Engine.Razor.AddTemplate("templateKey", template);
                    // Compiling templates 
                    Engine.Razor.Compile("templateKey", null);

                    await next.Invoke();
                }
               
            });

What I set up here is .net core MVC project , stay Stratup.cs  Of   Configure in Added a middleware for registering templates

It is worth noting that : Engine.Razor.AddTemplate("templateKey", template);    In this sentence  templateKey Set a unique identifier for the template     Then we can pass this key Direct access to The cache Templates , Without having to compile again .

 

3. Acquisition of database related information

What I'm using here is MySql database , Different databases can be modified or expanded by themselves , The following are the core methods related to database :

// Get the database list

        /// <summary>
        ///  Get the database list 
        /// </summary>
        /// <returns></returns>
        public static List<string> GetDbs()
        {
            string showdbSql = "SHOW DATABASES;";

            List<string> dbNames;

            using (var dbconn = DbHelper.GetConn())
            {
                dbNames = dbconn.Query<string>(showdbSql).ToList();
            }
            return dbNames;
        }

 

// Get the data table under the database

        /// <summary>
        ///  Get the data table under the database 
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public static List<string> GetTables(string dbName)
        {
            List<string> tableNames;

            string sql = [email protected]"select table_name from information_schema.tables where table_schema='{dbName}'";

            using (var dbconn = new MySqlConnection(DbHelper.ConnInUse))
            {
                tableNames = dbconn.Query<string>(sql).ToList();
            }

            return tableNames;
        }

// Get the fields in the data table

 /// <summary>
        ///  Get table parameter details 
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        private static TableInfo GetParameterInfos(string dbName, string tableName)
        {
            TableInfo tableInfo = new TableInfo(tableName);
            tableInfo.Parameters = new List<DbParamInfo>();
            tableInfo.Desc = GetTableDesc(dbName,tableName);

            using (var conn = DbHelper.GetConn())
            {
                string sql = [email protected]"
                                  SELECT 
                                  `information_schema`.`COLUMNS`.`COLUMN_NAME`,
                                  `information_schema`.`COLUMNS`.`DATA_TYPE`,
                                  `information_schema`.`COLUMNS`.`COLUMN_COMMENT`
                                  FROM `information_schema`.`COLUMNS`
                                  WHERE `information_schema`.`COLUMNS`.`TABLE_SCHEMA` ='{dbName}' 
	                              and `information_schema`.`COLUMNS`.`TABLE_NAME` = '{tableName}'
                            ";
                using (var reader = conn.ExecuteReader(sql))
                {
                    while (reader.Read())
                    {
                        var paramName = reader["COLUMN_NAME"].ToString();
                        var paramType = reader["DATA_TYPE"].ToString();
                        var desc = reader["COLUMN_COMMENT"].ToString();

                        tableInfo.Parameters.Add(new DbParamInfo
                        {
                            ParamName = paramName,
                            ParamType = GetCLRType(paramType),
                            Desc = desc
                        });
                    }
                }

                return tableInfo;
            }
        }

4. The main methods of generating entity files

        /// <summary>
        ///   The generated code 
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static string GenerateModel(string dbName,string tableName)
        {
            var data = GetParameterInfos(dbName, tableName);
            var result = Engine.Razor.Run("templateKey", null, data);
            return result;
        }

        /// <summary>
        ///  Get the field type according to the database type 
        /// </summary>
        /// <param name="dbType"></param>
        /// <returns></returns>
        private static string GetCLRType(string dbType)
        {
            switch (dbType)
            {
                case "tinyint":
                case "smallint":
                case "mediumint":
                case "int":
                case "integer":
                    return "int";
                case "bigint":
                    return "long";
                case "double":
                    return "double";
                case "float":
                    return "float";
                case "decimal":
                    return "decimal";
                case "numeric":
                case "real":
                    return "decimal";
                case "bit":
                    return "bool";
                case "date":
                case "time":
                case "year":
                case "datetime":
                case "timestamp":
                    return "DateTime";
                case "tinyblob":
                case "blob":
                case "mediumblob":
                case "longblog":
                case "binary":
                case "varbinary":
                    return "byte[]";
                case "char":
                case "varchar":
                case "tinytext":
                case "text":
                case "mediumtext":
                case "longtext":
                    return "string";
                case "point":
                case "linestring":
                case "polygon":
                case "geometry":
                case "multipoint":
                case "multilinestring":
                case "multipolygon":
                case "geometrycollection":
                case "enum":
                case "set":
                default:
                    return dbType;
            }
        }

5. Auxiliary method of template file

        /// <summary>
        ///  Initial lowercase 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FirstToLow(string str)
        {
           return str.Substring(0, 1).ToLower() + str.Substring(1);
        }

        /// <summary>
        ///  title case 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FirstToUp(string str)
        {
            return str.Substring(0, 1).ToUpper() + str.Substring(1);
        }

6. Template file

@using System
@using CodeHelper.Common
using using System;
namespace CodeHelper
{
    /// <summary>
    /// @Model.Desc
    ///</summary>
    public class @ModelHelper.FirstToUp(Model.TableName)
    {
        @foreach (var pm in  Model.Parameters)
        {
            @:/// <summary>
            @:/// @Raw(pm.Desc)
            @:/// <summary>
            @:private @pm.ParamType @ModelHelper.FirstToLow(pm.ParamName);
            @:
        }

        @foreach (var pm in  Model.Parameters)
        {
            @:public @pm.ParamType @ModelHelper.FirstToUp(pm.ParamName)
            @:{
            @:  get { return @ModelHelper.FirstToLow(pm.ParamName); }
            @:  set { @ModelHelper.FirstToLow(pm.ParamName) = value; }
            @:}
            @:
        }
    }
}

Razor Grammar is not introduced too much here


3、 ... and 、 Effect display

gitee Project address :https://gitee.com/tomato23132313/code-helper

 

summary

Here is only a very basic function , There is also a lot of extensible content , for example :

Selection of multiple templates 、 Dynamic configuration 、 Add property labels to entities 、 wait

 

版权声明
本文为[Tomato Warrior]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230553457651.html