.net-corevisual-studio-2022code-generationcode-firstcodegencs

How To Generate View Models From Code-First Entity Classes Using CodegenCS?


I have a set of entity classes for a Code-First approach. Is it possible to use CodegenCS to generate View Models from these class definitions? I am finding it difficult to figure out a way, let alone the best way, to reference the entity classes in a CodegenCS template in order to generate their View Model counterparts. I've found it impossible (hopefully actually not) to reference other classes unless they're defined within the template file itself.

I'm looking to use just one template from which to generate multiple outputs, as defining one template per entity to generate its View Model would feel like redundant work to me, and I may as well just manually create them instead. Further; if the above can be achieved using CodegenCS, I have bigger ideas beyond just generating View Models.

Thanks in advance!

TECH: I am using the CodegenCS extension for Visual Studio 2022, and .NET 7.0 (addendum: the project being used is a Class Library).

NOTE: I've been able to accomplish the above, and much more, using T4 templates, but I'm looking for an easier way to manage doing so considering the complexity and awkwardness of using T4 templates to generate multiple outputs via one template. I'm hoping CodegenCS is an avenue to simplifying code generation/scaffolding for my future projects.


Solution

  • I'm the author of CodegenCS, but I mostly use it based on Database schemas or Swagger definitions.

    What you describe (generate based on classes) should be done by creating a Roslyn Source Generator which during build time can iterate through your POCOs and "augment" the project by generating the new files

    UPDATE: Now we have a Source Generator. Check this - it saves you from the hassle of writing your own source generator, and you can rely on all CodegenCS features

    Feel free to open an issue in GitHub if you need more help.