Introduction
While working with the Entity Framework, view generation may take longer for a large and complicated model. When an ObjectContext object is initially created in a new application domain, the Entity Framework generates a set of classes that access the database. The generation of this view may take longer. It may delay the response of the first request for the page after initializing the application domain. The performance of view generation not only depends on the size of the model but also how complicated or interconnected it is. We can reduce this first time delay by creating the view at compile time instead of runtime.
The Entity Framework executes a query against a conceptual model or saves changes to the data source, so it must generate a set of views to access the database. This view is part of the metadata and cached per application domain. Within the same application domain the cached view can be reused. We can use the EdmGen.exe command line tool to generate precompiled / pre-generated views in the Entity Framework.
Procedure to create compile-time pre-generated views
Create compile-time pre-generated views using the following:
- Set the "Metadata Artifact Processing" property to "Copy to Output Directory"
This will ensure that the model and mapping files are generated in the output directory. The result of this is that now you are able to see the .ssdl, .csdl and .msl files in the output directory (i.e. "bin\Debug").
- Need to set up a pre-build event of the project (i.e. Edit project property, add the following pre-build event, without line breaks)
Note: In the following command you must replace the "EdmGen.exe" path as well as set the appropriate name of your model generated view.
"%windir%\Microsoft.NET\Framework\v4.0.30319\EdmGen.exe" /nologo /language:CSharp /mode:ViewGeneration "/inssdl:$(TargetDir)EntityModel.ssdl" "/incsdl:$(TargetDir)EntityModel.csdl" "/inmsl:$(TargetDir)EntityModel.msl" "/outviews:$(ProjectDir)EntityModel.Views.cs"
- Build the project which containing the Entity Model
After a successful build, the "EntityModel.Views.cs" file is available in the project root folder. Include this file in the project.
Conclusion
This article helps us to learn the use of the pre-generated view and how to set it up in our project. Using pre-generated we can improve the performance of the Entity Framework.