Entity Framework Core 自定义脚手架 [英] Entity Framework Core Customize Scaffolding
问题描述
我已经搭建了我的 SQLServer 数据库.并在指定的文件夹中创建 POCO 对象.我想做的是它从我的基类扩展而来.我也使用存储库模式,所以我需要在每个实体上都有 Id 键,我不想在每次重新构建数据库时都改变它.
I have done scaffolding of my SQLServer database. And it creates the POCO objects in the specified folder. What i would like to do is that it extends from my base class. I also use repository pattern so i need to have Id key on every entity and I don't want to change that each time i rescaffold the database.
脚手架模型示例
public partial class Food
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
预期结果:
public partial class Food : EntityBase
{
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
public class EntityBase : IEntityBase
{
public int Id { get; set; }
}
推荐答案
您可以使用 DbContextWriter &EntityTypeWriter 自定义sc输出.
You can use DbContextWriter & EntityTypeWriter to customize scaffold output.
- DBContextWriter ==>> CSharpDbContextGenerator
- EntityTypeWriter ==>> CSharpEntityTypeGenerator
编写一些自定义类型编写器,您可以覆盖所有内容并获得自己的代码生成器:
Write some custom type writer, you can override everything and you will get your own code generator:
//HERE YOU CAN CHANGE THE WAY TYPES ARE GENERATED AND YOU CAN ADD INTERFACE OR BASE CLASS AS PARENT.
public class CustomEntitiyTypeWriter : EntityTypeWriter
{
public CustomEntitiyTypeWriter([NotNull] CSharpUtilities cSharpUtilities)
: base(cSharpUtilities)
{ }
// Write Code returns generated code for class and you can raplec it with your base class
public override string WriteCode([NotNull] EntityConfiguration entityConfiguration)
{
var classStr = base.WriteCode(entityConfiguration);
var defaultStr = "public partial class " + entityConfiguration.EntityType.Name;
var baseStr = "public partial class " + entityConfiguration.EntityType.Name + " : EntityBase";
classStr = classStr.Replace(defaultStr, baseStr);
return classStr;
}
}
在设置中声明:
public static void ConfigureDesignTimeServices(IServiceCollection services)
=> services.AddSingleton<EntityTypeWriter, CustomEntitiyTypeWriter>();
然后脚手架db,你可以用CustomDBContextWriter对DBContext做同样的事情.
and then scaffold db, you can do the same for DBContext with CustomDBContextWriter.
这篇关于Entity Framework Core 自定义脚手架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!