Although Microsoft provided the T4 template, I found it very difficult to use. There’s no better way to write a template from a script.

Because to build tools around an old project, you need to connect to the database.

I used to use EntityFrameworkCore, because after all, I’ve been using an ORM since I started.

In the EF6 era, vs provided dbfirst, but only for sqlserver.

Since the database is MySQL this time, vs doesn’t support a lot of things.

But if you don’t have enough support, feed yourself.


 

We use the ejS template engine for the generator.

npm install ejs
Copy the code

Then use the query to find the table structure:

b.query('desc posts').then(res => {

})
Copy the code

Then write templates, EJS template syntax and ASPX era template syntax is very similar, are Angle brackets + percent sign such style <%%>, BELIEVE that have ASPX development experience of the old iron people to this template engine is very used to

using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; Public class <%= table -%> {<% rows.forEach(function(row){-%> <% if(row.type.indexof ('bigint'))! =-1){ -%> public long <%= row.Field %> { get; set; } <% } -%> <% if(row.Type.indexOf('datetime')! =-1){ -%> public DateTime <%= row.Field %> { get; set; } <% } -%> <% if(row.Type.indexOf('varchar')! =-1){ -%> public string <%= row.Field %> { get; set; } <% } -%> <% if(row.Type.indexOf('mediumtext')! =-1){ -%> public string <%= row.Field %> { get; set; } <% } -%> <% if(row.Type.indexOf('bit')! =-1){ -%> public bool <%= row.Field %> { get; set; } <% } -%> <% if(row.Type.indexOf('longtext')! =-1){ -%> public string <%= row.Field %> { get; set; } <%} -%> <%}); - % >}}Copy the code

In the above template, there are C# type mappings for different MySQL data types.

Then use EJS to render a text and save it to a folder

Var tableName = 'tableName '; Ejs.renderfile ('./template/posts.ejs', {rows: res.rows, 'table': tableName}, (err, str) => { if (err) { console.error(err); } else { let temp = path.join(__dirname, 'temp'); var exist = fs.existsSync(temp) if (! exist) { fs.mkdirSync() } fs.writeFile(path.join(temp, tableName+'.cs'), str, (err) => { if (err) { console.error(err); } else {console.log(' Template generated successfully '); }})}})Copy the code

Execute with Node to generate a CS file.

Since I don’t have many tables, I’ll just generate them individually. If you want to scale the entire database, you can write a few lines of code to generate the entire library!


 

Old iron people who need to communicate can click the link below the blog or directly search the group number to join the QQ group :545594312