A few day ago, a colleague of mine, Shlomo Goldberg, raised a question about Entity Framework and large models. Another colleague of mine, Gil Fink posted some links to helpful tips for using large models, and I want to talk about one of these tips – using the View Generation option.
If you’ve worked with large models in Entity Framework 3.5, you probably noticed that as the model grows, it takes more time to initialize the ObjectContext for the first time. A solution to this is to use view generation, using the EdmGen tool, which can reduce up to 30% of the time it takes to initialize the context for the first time.
If you’ve tried to use the view generation for very large models (80+ entities), you probably noticed that the generation it self takes a lot of time to complete, the output code file is very large (we’ve reached up to 70Mb) and if the model is very large and complex (large inheritance trees are a big contributor), the generated file can sometimes makes Visual Studio crash on opening and compiling.
If you look at the generated file content, you’ll see that it includes many if/else/if statements, that looks something like this:
if (index == 0)
{
}
else
{
if (index == 1)
{
}
else
{
…
}
}
This structure of code is problematic for the following reasons:
-
It creates a very large if/else/if tree, that at some point cannot be translated by the compiler
-
The canonical if/else/if will sometimes cause Visual Studio to crash (I assume whoever created VS didn’t think someone will use that many if/else/if statements)
-
The whitespaces used to create this form causes the size of the file to be extremely large
So what can you do?
You can move to Entity Framework 4.0 (currently in beta) where the view generation was fixed. In EF4 the generated code is of the form:
if (index == 0)
{
}
if (index == 1)
{
}
If you can’t or don’t want to move to EF4, you can edit the generated file and change the structure of the code to make it similar to the one generated by EF4 (remove brackets and whitespaces). Since this file can be auto generated and it’s a waste of time doing find & replace, I’ve attached a
Powershell script that performs the changes. Using this script can reduce the generated file size a lot (sometimes up to 90% reduction of file size).
If you’re interested in learning more about Entity Framework or about ORM in general, we’ll be discussing these topics and more in the SDP on 27-30 of December.
This week I’ll continue to write more posts about Entity Framework Tips & Tricks, directly from the PDC (Los-Angeles), and hopefully some of these posts will contain new insight to Entity Framework 4.0 and future roadmap