实体框架核心自定义脚手架 [英] Entity Framework Core Customize Scaffolding

查看:63
本文介绍了实体框架核心自定义脚手架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经完成了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.

Scaffold模型示例

Scaffold Model Example

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; }
}


推荐答案

您可以使用 DbContextWamper EntityTypeWriter 进行定制输出。

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.

这篇关于实体框架核心自定义脚手架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆