Search code examples
c#visual-studio-2019ef-core-3.0

How do I pull CSharpEntityTypeGenerator into the project?


I've seen lots of posts talking about how to subclass CSharpEntityTypeGenerator to modify what EF Core writes out. Visual studio doesn't like that and says to install Microsoft.EntityFrameworkCore.Design. I've installed v3.1.0-preview1.19506.2.

However, VS still says that it can't find that class and to install the NuGet package.

What's the magic to make this work?

I'm wanting to write a class like this so that #nullable disable is added and the GeneratedCode attribute is inserted.

public class EntityTypeGenerator : CSharpEntityTypeGenerator
{
    public EntityTypeGenerator(ICSharpHelper helper) : base(helper) { }

    public override string WriteCode(IEntityType type, string @namespace, bool useDataAnnotations)
    {
        var code = base.WriteCode(type, @namespace, useDataAnnotations);

        var old = "public partial class " + type.Name;
        var updated = "[System.CodeDom.Compiler.GeneratedCode]\n" + old;

        return code.Replace(old, updated).Replace("namespace", "#nullable disable\n\nnamespace");
    }
}

Solution

  • Update the reference in your project file:

    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0">
      <PrivateAssets>all</PrivateAssets>
      <!-- Remove IncludeAssets to allow compiling against the assembly -->
      <!--<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>-->
    </PackageReference>