Pre-Generating Entity Framework Views with Embedded Metadata

Problem: When you are using embedded metadata in your Entity Framework project, the MSDN topic for How to: Pre-Generate Views to Improve Query Performance (Entity Framework) comes up short.

Solution: This posting shows a simple (if tedious) technique for working with both embedded metadata and the pre-generated views.

Step 1: Edit the XML of your EDMX file, down near the bottom, locate the Designer tag:

<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2007/06/edmx">
    <edmx:Connection>
      <DesignerInfoPropertySet>
        <DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
      </DesignerInfoPropertySet>
    </edmx:Connection>

Change this by adding an XML Comment to the DesignerInfoPropertySet tag:

<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2007/06/edmx">
    <edmx:Connection>
      <DesignerInfoPropertySet>
        <!--DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" /-->
        <!--DesignerProperty Name="MetadataArtifactProcessing" Value="CopyToOutputDirectory" /-->
        <DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
      </DesignerInfoPropertySet>
    </edmx:Connection>

Step 2: Edit the Project Properties | Build Events. Add a pre-build event:

rem "%windir%\Microsoft.NET\Framework\v3.5\EdmGen.exe" /nologo /language:CSharp /mode:ViewGeneration "/inssdl:$(TargetDir)ServerModel.ssdl" "/incsdl:$(TargetDir)ServerModel.csdl" "/inmsl:$(TargetDir)ServerModel.msl" "/outviews:$(ProjectDir)ServerModel.Views.cs"

Now, at this point the projects are relatively unchanged, you’ve added a comment to the EDMX file and a comment to the Build Events. During active Entity Model changes you should leave these comments in place. Once the model is stable (more-or-less), you can pre-generate the views.

To Pre-generate the Views:
Step 1: Edit the EDMX file and change the DesignerProporty tag to CopyToOutputDirectory:

<DesignerProperty Name="MetadataArtifactProcessing" Value="CopyToOutputDirectory" />

Step 2: Uncomment the build event:

"%windir%\Microsoft.NET\Framework\v3.5\EdmGen.exe" ...

Step 3: Build the Project. The build will now generate the ServerModel.Views.cs file.

Step 4: Add the (now) Existing Item “ServerModel.Views.cs” into your Entity Model project.

Step 5: Reverse the changes made in Step 1 and Step 2. (Changing CopyToOutputDirectory back to EmbedInOutputAssembly, and adding REM back in front of the build event.

As I said, it’s tedious, however, it works. Smarter folks than me can probably automate it. (If you do, I’d love to know how.)