当前位置:网站首页>.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
边栏推荐
- ClickHouse-SQL 操作
- Devexpress GridView add select all columns
- 2. Electron's HelloWorld
- Calculation formula related to tolerance analysis
- Error in v-on handler: "typeerror: cannot read property 'resetfields' of undefined"
- Shell script -- shell programming specification and variables
- MySQL master-slave configuration under CentOS
- Wiper component encapsulation
- PHP efficiently reads large files and processes data
- Node access to Alipay open platform sandbox to achieve payment function
猜你喜欢
Document operation II (5000 word summary)
JS, entries(), keys(), values(), some(), object Assign() traversal array usage
【WPF绑定3】 ListView基础绑定和数据模板绑定
VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN
C# Task. Delay and thread The difference between sleep
快时钟同步慢时钟域下的异步控制信号slow clk to fast clk
Simulation of infrared wireless communication based on 51 single chip microcomputer
[PROJECT] small hat takeout (8)
[WPF binding 3] listview basic binding and data template binding
Detailed explanation of C webpai route
随机推荐
Website_ Collection
MySQL master-slave configuration under CentOS
feign报400处理
【解决报错】Error in v-on handler: “TypeError: Cannot read property ‘resetFields’ of undefined”
文件操作《二》(5000字总结篇)
El cascade and El select click elsewhere to make the drop-down box disappear
VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN
Generation of barcode and QR code
【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明
[PROJECT] small hat takeout (8)
oracle 中快速获取表的列名列表
Detailed explanation of C webpai route
Bottom processing of stack memory in browser
[C#] 彻底搞明白深拷贝
groutine
New keyword learning and summary
Lock锁
Use of Shell sort command
Milvus 2.0 质量保障系统详解
手写事件发布订阅框架