我设法完成了这项工作并更新了以下内容以展示我是如何做到的。如果有更优雅的解决方案,我感兴趣:)
前言:我正试图从Entity Framework 6迁移到Entity Framework Core。我有一个现有的数据库。我正在做数据库第一代。我使用" scaffold-dbContext"生成类。在控制台中执行此命令。好的,没关系。但是我希望所有生成的类都从一个简单的基类继承。这是整个基类的要点:
public class MyEntityBase
{
public MyEntityBase()
{
}
}
因此,如果数据库中有一个名为customer的表,我希望生成的类开始于:
public partial class Customer : MyEntityBase
我可以通过更改相应位置的T4文件在EF6中执行此操作。我设法通过以下方式在EF Core中完成。
首先获得更多信息。在我的解决方案中,我有两个项目。一个是" Web" project,作为ASP.NET Core Web应用程序创建的。另一个是"核心" project,创建为.NET Core类库。这是Context文件和实体类将存在的位置。它也是MyEntityBase生活的地方。
好的,我在Web项目中添加了一个名为MyDesignTimeServices.cs的类文件。该文件的内容如下:
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Scaffolding.Internal;
using Microsoft.EntityFrameworkCore.Scaffolding.Configuration.Internal;
namespace MySolution.Web
{
public class MyDesignTimeServices : IDesignTimeServices
{
public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
{
//serviceCollection.AddSingleton<EntityTypeWriter, MyEntityTypeWriter>();
serviceCollection.AddSingleton<DbContextWriter, MyDbContextWriter>();
}
}
public class MyDbContextWriter : DbContextWriter
{
public MyDbContextWriter(ScaffoldingUtilities scaffoldingUtilities, CSharpUtilities cSharpUtilities) : base(scaffoldingUtilities, cSharpUtilities) { }
public override string WriteCode(ModelConfiguration modelConfiguration)
{
var code = base.WriteCode(modelConfiguration);
code = code.Replace("});", "\tentity.HasBaseType<" + typeof(MySolution.Core.MyEntityBase).Name + ">();" + Environment.NewLine + "\t\t\t});");
return code;
}
}
public class MyEntityTypeWriter : EntityTypeWriter
{
public MyEntityTypeWriter(CSharpUtilities cSharpUtilities) : base(cSharpUtilities) { }
public override string WriteCode(EntityConfiguration entityConfiguration)
{
// Get the default code of the entity class.
var code = base.WriteCode(entityConfiguration);
// We need to find the spot after the name of the class so we can add its inheritance.
var classDeclaration = "public partial class ";
var classDeclarationIndex = code.IndexOf(classDeclaration);
if (classDeclarationIndex != -1)
{
// Remove anything in front of the class name, so that we can look for the first carriage return.
var startsWithClassName = code.Substring(classDeclarationIndex + classDeclaration.Length);
var afterClassNameIndex = startsWithClassName.IndexOf((char)13);
if (afterClassNameIndex != -1)
{
// This is the spot where we want to insert our inheritance declaration.
var insertIndex = classDeclarationIndex + classDeclaration.Length + afterClassNameIndex;
// Insert our inheritance declaration.
code = code.Substring(0, insertIndex) + " : " + typeof(MyEntityBase.Core.MyEntityBase).Name + code.Substring(insertIndex);
}
}
return code;
}
}
}
构建解决方案。然后,当我在包管理器控制台中运行Scaffold-DbContext命令时,我确保将Default project下拉选项设置为Core项目。