So i have my migrations folder from ef core right? But my IDE style code throws a bunch of errors in the generated files, so i need to manually insert the // comment, so everything is ignored. Is there any way, that whenever a new migration is added to add this automatically?
You can do this by creating your own custom CSharpDbContextGenerator
and CSharpEntityTypeGenerator
classes. For example:
public class MyContextTypeGenerator : CSharpDbContextGenerator
{
public MyContextTypeGenerator(
IProviderConfigurationCodeGenerator providerConfigurationCodeGenerator,
IAnnotationCodeGenerator annotationCodeGenerator,
ICSharpHelper cSharpHelper) : base(providerConfigurationCodeGenerator, annotationCodeGenerator, cSharpHelper)
{
}
public override string WriteCode(
IModel model,
string contextName,
string connectionString,
string contextNamespace,
string modelNamespace,
bool useDataAnnotations,
bool useNullableReferenceTypes,
bool suppressConnectionStringWarning,
bool suppressOnConfiguring)
{
var builder = new IndentedStringBuilder();
// Add your own code to the start
builder.AppendLine("// <auto-generated>");
// Add the default code be generated
builder.Append(base.WriteCode(model, contextName, connectionString, contextNamespace, modelNamespace, useDataAnnotations, useNullableReferenceTypes, suppressConnectionStringWarning, suppressOnConfiguring));
return builder.ToString();
}
}
And for the entities:
public class MyEntityTypeGenerator : CSharpEntityTypeGenerator
{
public MyEntityTypeGenerator(IAnnotationCodeGenerator annotationCodeGenerator, ICSharpHelper cSharpUtilities)
: base(annotationCodeGenerator, cSharpUtilities)
{
}
public override string WriteCode(IEntityType entityType, string @namespace, bool useDataAnnotations, bool useNullableReferenceTypes)
{
var builder = new StringBuilder();
builder.AppendLine("// <auto-generated>");
builder.Append(base.WriteCode(entityType, @namespace, useDataAnnotations, useNullableReferenceTypes));
return builder.ToString();
}
}
Then you need to ensure the types gets used by EF, so add this class too:
public class MyDesignTimeServices : IDesignTimeServices
{
public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<ICSharpDbContextGenerator, MyContextTypeGenerator>();
serviceCollection.AddSingleton<ICSharpEntityTypeGenerator, MyEntityTypeGenerator>();
}
}
Note 1: You probably also need to add the Microsoft.EntityFrameworkCore.Design
Nuget package.
Note 2: This will give you a warning about using EF Core internal classes which you can disable with:
#pragma warning disable EF1001