Performance Optimization with Pre-generate Entity Framework Views

Using Entity Framework in either ways of CodeFirst or ModelFirst give us benefits on creating object models and save lots time on data access programming. But during the application initial load, Entity Framework takes time to look up the schema especially hundreds tables and relationships to generate views. View generation is known to be slow for bigger models. For now the solution is to use pregenerated views. This way we generate views at design time and avoid this work at run time.

When working with Entity Framework 4 one of the potential optimizations is to use pre-compiled views where Entity Framework query views are pre-built and compiled into the application; which otherwise, the entity framework would have to generate on the fly (extra resources being required). It warms up a system and the execution of infrequently run queries. The use of less memory is also advantageous and is due to no longer having the overhead of keeping and creating the views.

There are two ways to generate views from Entity Framework.

  1. Use the Text Template Transformation Toolkit to generate pre-compiled views. For more information, see “How to use a T4 template for View Generation” or “T4 TEMPLATES FOR GENERATING VIEWS FOR EF4/EF5 CODE FIRST APPS ” and “T4 TEMPLATES FOR GENERATING VIEWS FOR EF4/EF5 DATABASE/MODEL FIRST APPS
  2. Use the EDM Generator (EdmGen.exe) tool to pre-generate views. In my practice, I found T4 template is very convenient but doesn’t work with IoC containers in dependency injection design pattern as the signature generated doesn’t match when creating instances of classes that implement a given dependency interface on request. The views generated by EdmGen.exe works well. Following sample shows how to warm up a CodeFirst Entity Framework project and use EdmGen.exe to pre-generate views then add the view file to the project.
  • In Global.asax, create a function RegenerateEntityFrameworkViews().
  • In Application_Start(), call above function to generate artifacts for your context “Context.ssdl”, “Context.csdl”, “Context.msl”.
  • Use EdmGen tool to generate views from above artifacts. I need to do it from the VS Command prompt. Here is the command I use to generate views: EdmGen /nologo /language:CSharp /mode:ViewGeneration /inssdl:Context.ssdl /incsdl:Context.csdl /inmsl:Context.msl /outviews:Model1.Views.cs
  • Add the generated file to the project under Models then compile.
  • Run RegenerateEntityFrameworkViews function every time when database changed, otherwise comment it out.

18-12-2013 -1

This entry was posted in Entity Framework, Information Technology, MVC and tagged , , , , . Bookmark the permalink.