dbfirst下让efcore生成的model继承于一个公共的类

89 篇文章 0 订阅
11 篇文章 0 订阅

)1 Make entities inherit from a base class in Entity Framework Core DB First

https://davecallan.com/make-entities-inherit-base-class-in-entity-framework-core-db-first/

通过EF Core Power Tools

vs扩展插件实现

1.1)安装扩展Install the extension

via the Extensions -> Manage Extensions window (you’ll then see the menu as a right-click option on your projects).

Right click on the relevant project and select EF Core Power Tools -> Reverse Engineer and first select which tables you want to scaffold and then on the subsequent screen check the option for customizing the code.

Reverse Engineer

After running the scaffolding you should see entities generated AND a CodeTemplates folder which contains all the handlebar template files for customizing entities and the DbContext.

To inherit from a base class just amend the Class template (Class.hbs) file as shown on the left below.

Inherit from a base class

Re-scaffold again with right click -> EF Core Power Tools -> Reverse Engineer and all your entities should now inherit from the base class

Entity inheriting base class example

Of course to have your entities implement an interface the process is identical.

2)自建模板实现

如果您使用 dotnet ef dbcontext scaffold 命令来自动生成实体类,并希望这些生成的实体类继承自一个公共的基类,可以通过自定义代码模板来实现。

以下是一种实现方式:

  1. 创建一个公共的基类,例如 BaseEntity,其中包含您希望的通用属性和方法。
public class BaseEntity
{
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }
    // 其他通用属性和方法...
}
  1. ,通过使用自定义的代码模板,您可以生成的实体类都会继承自指定的公共基类 BaseEntity
  2.   

请根据您的实际情况更新命令中的参数和文件路径,并根据需要对模板进行自定义。确保在生成实体类之后进行适当的测试和验证,以确保它们符合预期并满足您的需求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值