使用AddHandlebarsScaffolding与EF时如何忽略指定实体类的脚手架生成?
问题
我通过scaffold命令自定义类,已经写好Class.hbs模板和对应的C#配置代码,当前配置能给所有生成的类添加自定义内容,但现在想忽略部分实体类的脚手架生成,该怎么实现?
模板代码(Class.hbs)
{{> imports}} {{using-base-class}} namespace {{namespace}} { {{#if comment}} /// <summary> {{comment}} /// </summary> {{/if}} {{#each class-annotations}} {{{class-annotation}}} {{/each}} public partial class {{class}} {{base-class}} { {{{> constructor}}} {{{> properties}}} } }
C#配置代码
public void ConfigureDesignTimeServices(IServiceCollection services) { services.AddHandlebarsScaffolding(options => { options.TemplateData = new Dictionary<string, object> { { "using-base-class", "using TEST_NET_7.Interface;" }, { "base-class", ": IEntityId" } }; }); }
解决方案
方法1:命令行直接排除
执行scaffold命令时,用--exclude参数指定要跳过的实体类(对应数据库表名或类名,依EF Core映射规则而定):
Scaffold-DbContext "你的连接字符串" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models --exclude TableName1,TableName2
方法2:模板内加条件判断
修改Class.hbs模板,通过Handlebars条件语法跳过指定类的生成:
{{#unless (or (eq class "IgnoreClass1") (eq class "IgnoreClass2"))}} {{> imports}} {{using-base-class}} namespace {{namespace}} { {{#if comment}} /// <summary> {{comment}} /// </summary> {{/if}} {{#each class-annotations}} {{{class-annotation}}} {{/each}} public partial class {{class}} {{base-class}} { {{{> constructor}}} {{{> properties}}} } } {{/unless}}
只要类名匹配IgnoreClass1或IgnoreClass2,模板就会输出空内容,等同于跳过该类的生成。
方法3:自定义模板生成器过滤
在配置代码中替换默认模板生成器,加入实体过滤逻辑:
public void ConfigureDesignTimeServices(IServiceCollection services) { services.AddHandlebarsScaffolding(options => { options.TemplateData = new Dictionary<string, object> { { "using-base-class", "using TEST_NET_7.Interface;" }, { "base-class", ": IEntityId" } }; }); // 替换默认生成器,添加过滤规则 services.Replace(ServiceDescriptor.Scoped<IHandlebarsTemplateGenerator, FilteredTemplateGenerator>()); } public class FilteredTemplateGenerator : HandlebarsTemplateGenerator { private readonly IHandlebarsHelpers _helpers; private readonly IHandlebarsTemplateOptions _options; public FilteredTemplateGenerator(IHandlebarsHelpers helpers, IHandlebarsTemplateOptions options) : base(helpers, options) { _helpers = helpers; _options = options; } public override string GenerateTemplate(TemplateType templateType, ModelTemplateData modelData) { // 定义需要忽略的类名列表 var ignoredClasses = new List<string> { "IgnoreClass1", "IgnoreClass2" }; if (templateType == TemplateType.Class && ignoredClasses.Contains(modelData.ClassName)) { return string.Empty; // 返回空内容,跳过生成 } return base.GenerateTemplate(templateType, modelData); } }
方法4:通过DbContext模型过滤
在DbContext的OnModelCreating方法中忽略指定实体或表,这样脚手架不会为其生成类(同时会影响EF Core的模型映射):
protected override void OnModelCreating(ModelBuilder modelBuilder) { // 忽略实体类 modelBuilder.Ignore<IgnoreClass1>(); modelBuilder.Ignore<IgnoreClass2>(); // 或者直接忽略数据库表 modelBuilder.Entity("TableName1").Ignore(); }
内容的提问来源于stack exchange,提问作者TyDialexno
相关产品推荐
相关产品推荐

