Once Entity Framework was released few months ago, the first question in my mind was: why Microsoft released a new version of EF6 when the main new branch is EF Core?
What the necessity that force the team to release a new version could be?
Well, EF 6.2 contains a bunch of new improvements, for example now we are able to use the DbFunctions.Like() in our LINQ query, that will be translated to the SQL LIKE.
But in my opinion, the principal enhancement is the startup time speedup, reached through the generation of a persistent cache of the code first models; this feature has been implemented by providing a specific configuration of the DbContext, that once enabled will save the serialized models in a local edmx file, that will be used by the framework at the startup.
Configuration
The configuration is very simple and consists to create a new class in the same assembly of the context, derive the new base class DbConfiguration and define the edmx location in the class constructor:
public class CoreContextConfiguration : DbConfiguration { public CoreContextConfiguration() : base() { var modelStoreDir = AppDomain.CurrentDomain.BaseDirectory + @"\edmx\"; if (!Directory.Exists(modelStoreDir)) Directory.CreateDirectory(modelStoreDir); this.SetModelStore(new DefaultDbModelStore(modelStoreDir)); } }
In the first row I retrieve the base assembly directory and I append the edmx path.
Then I check if the directory exists, otherwise I create it.
The last step is set the context model store with a new object of type DefaultModelStore, instantiated with the parameter of the edmx path.
After that my configuration is ready and I can check that the edmx file is generated with a test method.
Test
I create a new class library and I implement a simple test method:
[TestFixture] public class ContextTest { [Test] public async Task CreateBlogs() { using (var db = new CoreContext()) { for (int i = 0; i < 1000; i++) { var blog = new Blog() { Name = "Test" }; db.Blogs.Add(blog); } await db.SaveChangesAsync(); } } }
After running the method, if my configuration is good, I’ll find the edmx file in my assembly directory:
Performance improvements
The startup time is always been the main defect of Entity Framework.
With this improvement, just to get an idea, we can refer to the link of the GitHub issue referenced above; with a context of over than 600 models, the startup time is dropped from 12/14 seconds to 2 seconds….
We are talking about completely different performance, even because this is one of the main reasons that a new version of EF6 was released.
Leave a Reply