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

160 Views Asked by At

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.

1

There are 1 best solutions below

0
drizin On

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) can be done in two ways:

  • Build your POCOs and then create a CodegenCS that will read the DLL using reflection and generate what you need
  • Use a Roslyn Source Generator which let you (during build time) iterate through your POCOs and "augment" the project by generating the new files

Check these two links: https://github.com/CodegenCS/CodegenCS/blob/master/docs/Comparison-Roslyn.md https://github.com/CodegenCS/Samples/tree/main/src/SampleSourceGenerator.SimplePocos

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