Custom T4 Template Code Generation for EF Core

2024年5月7日 16点热度 2人点赞 0条评论
内容目录

T4 Template Files

The first step is to set up T4 template files in the project.

If you are unfamiliar with T4 templates, you can look up information or visit https://learn.microsoft.com/zh-cn/visualstudio/modeling/code-generation-and-t4-text-templates?view=vs-2022.

You can use tools to generate two template files.
Install the template tool:

dotnet new install Microsoft.EntityFrameworkCore.Templates

Then, execute the command in the project directory to create the template files:

dotnet new ef-templates

After executing the command, the following structure will be generated:

├─CodeTemplates
│  └─EFCore
│          DbContext.t4
│          EntityType.t4

The directory structure must be designed like this. In addition to these two files, you can also add other template files.

Please refer to third-party template files: https://github.com/R4ND3LL/EntityFrameworkRuler/tree/main/src/EntityFrameworkRuler.Design/Resources

Execute Command to Generate Code

Execute the command to generate code from the database:

dotnet ef dbcontext scaffold "server=127.0.0.1;Database=aaa;Uid=root;Pwd=123456;" Pomelo.EntityFrameworkCore.MySql --context AAAContext --context-dir Data --output-dir Entities -f

Improve OnModelCreating

If there are many database tables, the OnModelCreating method in the context file will contain a large amount of configuration code, significantly affecting readability. We can use T4 templates to distribute these configurations to specific EntityTypeConfiguration files.

Download this file: https://github.com/R4ND3LL/EntityFrameworkRuler/blob/main/src/EntityFrameworkRuler.Design/Resources/EntityTypeConfiguration.t4

file

Re-execute the generation command:

file

All configurations will be automatically distributed to specific files.

痴者工良

高级程序员劝退师

文章评论