我正在使用EF Core和DB First方法。我使用Node.js
生成了dbcontext和entity类,它给了我预期的结果。
然后,我需要在dbcontext和实体类中添加自定义实现,但是每当我更新db并重新搭建它时,所有文件都会被替换,我所有的自定义实现也都消失了。如何使用上下文和实体同时使用一些自定义配置来构建框架?
这是我的目标示例
我有dotnet ef dbcontext scaffold
个课程
BaseEntity.cs
我的实体看起来像这样
public class BaseEntity
{
public int Id { get; set; }
public bool Deleted { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedTime { get; set; }
public string LastModifiedBy { get; set; }
public DateTime? LastModifiedTime { get; set; }
}
但是如果我重新搭建脚手架,它将变成
public partial class Education : BaseEntity
{
public Education()
{
EducationDetail = new HashSet<EducationDetail>();
}
public int UserProfileId { get; set; }
public int EnumEducationId { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public virtual EnumEducation EnumEducation { get; set; }
public virtual UserProfile UserProfile { get; set; }
public virtual ICollection<EducationDetail> EducationDetail { get; set; }
}
我可以定制脚手架吗?我找到了Entity Framework Core Customize Scaffolding,但是我认为它不再可用,也不受Microsoft支持
有什么办法吗?
答案 0 :(得分:1)
使用partial classes。 严格添加到类中时,此方法效果很好。不幸的是,它不适用于您的情况,因为某些生成的属性将需要override
基础成员。但是,如果您改用接口,它将起作用。
partial class Education : IEntity
{
}
使用模板。这使您可以完全控制所生成的代码。 EntityFrameworkCore.Scaffolding.Handlebars软件包通过handlebars启用模板。 EFCore.TextTemplating示例展示了如何使用T4 templates。
<#@ parameter name="EntityType" type="Microsoft.EntityFrameworkCore.Metadata.IEntityType" #>
<#@ parameter name="Code" type="Microsoft.EntityFrameworkCore.Design.ICSharpHelper" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="Microsoft.EntityFrameworkCore" #>
<#
var baseProperties = new[]
{
"Id",
"Deleted",
"CreatedBy",
"CreatedTime",
"LastModifiedBy",
"LastModifiedTime"
};
#>
public partial class <#= EntityType.Name #> : BaseEntity
{
<# foreach (var property in EntityType.GetProperties()
.Where(p => !baseProperties.Contains(p.Name))) { #>
public <#= Code.Reference(property.ClrType) #> <#= property.Name #> { get; set; }
<# } #>
}