当前位置:网站首页>.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
One 、RazorEngine.NetCore Basic use
3. Acquisition of database related information
4. The main methods of generating entity files
5. Auxiliary method of template file
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
边栏推荐
- Tencent resolves the address according to the IP address
- [WPF binding 3] listview basic binding and data template binding
- Self use learning notes - connected and non connected access to database
- Shell-cut命令的使用
- Clickhouse table engine
- Nodejs installation and environment configuration
- ASP. Net core configuration options (Part 2)
- Use of shell sed command
- Grpc gateway based on Ocelot
- PHP高效读大文件处理数据
猜你喜欢

VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN

自定义my_strcpy与库strcpy【模拟实现字符串相关函数】

Lock lock

Detailed explanation of the penetration of network security in the shooting range

Nacos + aspnetcore + Ocelot actual combat code

Node access to Alipay open platform sandbox to achieve payment function

Signalr can actively send data from the server to the client

Go language, array, string, slice

1-4 configuration executable script of nodejs installation

线性代数感悟之1
随机推荐
How does matlab draw the curve of known formula and how does excel draw the function curve image?
Shell-awk命令的使用
Decimal format decimal / datetime conversion processing
Clickhouse table engine
SQL database
Input file upload
Wiper component encapsulation
1-4 configuration executable script of nodejs installation
AIOT产业技术全景结构-数字化架构设计(8)
Generation of barcode and QR code
1-3 components and modules
STM32__ 03 - beginner timer
JS, entries(), keys(), values(), some(), object Assign() traversal array usage
org. apache. parquet. schema. InvalidSchemaException: A group type can not be empty. Parquet does not su
RTKLIB 2.4.3源码笔记
PostgreSQL column storage and row storage
New keyword learning and summary
2. Electron's HelloWorld
Handwritten event publish subscribe framework
Milvus 2.0 質量保障系統詳解