EF核心脚手架自定义实体和DBContext



我使用的是EF Core和DB First方法。我使用dotnet ef dbcontext scaffold生成了我的dbcontext和entities类,它给了我预期的结果。

然后,我需要在我的dbcontext和实体类中添加自定义实现,但每当我更新数据库并重新构建它时,所有文件都会被替换,我的所有自定义实现也会消失。如何用一些自定义配置同时构建上下文和实体?

下面是我瞄准的例子

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

但如果我重新搭建脚手架,它就会变成

public partial class Education 
{
public Education()
{
EducationDetail = new HashSet<EducationDetail>();
}
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 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; }
}

我可以定制脚手架吗?我发现实体框架核心自定义脚手架,但我认为它不再可用/支持微软

有什么办法吗?

选项1

使用分部类。当严格地将添加到类中时,这种方法效果很好。不幸的是,它不适合您的场景,因为生成的一些属性需要override基本成员。但是,如果您使用一个接口,它会起作用。

partial class Education : IEntity
{
}

选项2

使用模板。这使您能够完全控制生成的代码。EntityFrameworkCore.Caffolding.Handlebars包通过手把启用模板。EFCore.TextTemplateing示例显示了如何使用T4模板。

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

<# } #>
}

最新更新