I am using Entity Framework Core tools to create Entities and DBContext from the existing database.
Scaffold-DbContext "Server=XXXXXX;Database=MyDB;User ID=xxxx;Password=xxxxxxx" Microsoft.EntityFrameworkCore.SqlServer -ContextDir .-OutputDir Entities -Force
This working. But is there any way to scaffold all the entities with known interface? So i have interface IEntityBase
and i want all the entities to have this interface
Note This question is specific to EF Core 2+ and scaffolding
Update 1
So as per the SO Suggesion i have created CSharpEntityTypeGenerator
and IDesignTimeServices
The accepted answer is not valid for EF Core > 2.* so i am using the suggession from @Chris Peacock
public class MyEntityTypeGenerator: CSharpEntityTypeGenerator
{
public MyEntityTypeGenerator(ICSharpHelper cSharpHelper)
: base(cSharpHelper)
{
}
public override string WriteCode(IEntityType entityType, string @namespace, bool useDataAnnotations)
{
string code = base.WriteCode(entityType, @namespace, useDataAnnotations);
var oldString = "public partial class " + entityType.Name;
var newString = "public partial class " + entityType.Name + " : EntityBase";
return code.Replace(oldString, newString);
}
}
public class MyDesignTimeServices: IDesignTimeServices
{
public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<ICSharpEntityTypeGenerator, MyEntityTypeGenerator>();
}
}
There is one change i had to make. CSharpEntityTypeGenerator
constructor takes ICSharpHelper
as parameter instead of ICSharpUtilities
These two classes are in Data
assembly which is not a startup project.
At package manager console i executed the scaffolding command again. However i do not see generated entities have base class.
How scaffolding framework would know to use my custom generator? I am adding generator in serviceCollection
but looks like the code never get executed
Am i missing something?
You can use EF Core Power Tools with Handlebars templates to achieve this.
https://github.com/ErikEJ/EFCorePowerTools/wiki/Reverse-Engineering#customize-code-using-handlebars