When working with Entity Framework view generation may take a long time for bigger or complicated models. The workaround for this problem is to use pre-generated views. In case of Database First and Model First approaches you can use T4 templates that will create the pre-generated views (you can find more details here). But what to do when using Code First approach? One possibility is to use Entity Framework Power Tools – just right-click on the file containing your DbContext derived class and select “Optimize Data Model”. Voila – views are created. But what if you need more control, cannot use UI (e.g. you want your build system to create the pre-generated views) or the tool for whatever reason does not work? You can for instance follow this 5 steps:
- Get Edmx file for your model using EdmxWriter.WriteEdmx() method
- Retrieve csdl, msl, ssdl from the edmx file and save them
- From the Visual Studio Command Prompt run EdmGen with mode parameter set to ViewGeneration (i.e. /mode:ViewGeneration)
- Add the generated C#/VB.Net file to your project
- Repeat each time you change your model
Easy? Maybe. Error prone? Probably. Cumbersome? For sure. But now there is a third way. Similarly to the T4 templates for Model and Database First workflows I created T4 templates for creating pre-generated views for Code First approach. Now, you would just add the right (C# or VB.Net) template to your project, rename it so that it contains the name of the context you want to create the views for (e.g. MyContext.Views.tt) and generate your views by right clicking the template and selecting “Run Custom Tool” menu option. Note that creating the pre-generated views with the template will take approximately the same amount of time it takes to create views at runtime – you are just doing the work that would be done at runtime at design time. The templates are (temporarily) available here. I will update this post when they are moved to the final location.The templates are available on the Visual Studio Code Gallery. See this post for more details.
Pawel Kadluczka