Search code examples
performanceentity-frameworkentity-framework-4savechanges

Entity Framework SaveChanges() first call is very slow


I appreciate that this issue has been raised a couple of times before, but I can't find a definitive answer (maybe there isn't one!).

Anyway the title tells it all really. Create a new context, add a new entity, SaveChanges() takes 20 seconds. Add second entity in same context, SaveChanges() instant.

Any thoughts on this? :-)

============ UPDATE =============

I've created a very simple app running against my existing model to show the issue...

    public void Go()
    {
        ModelContainer context = new ModelContainer(DbHelper.GenerateConnectionString());

        for (int i = 1; i <= 5; i++)
        {
            DateTime start = DateTime.Now;
            Order order = context.Orders.Single(c => c.Reference == "AA05056");
            DateTime end = DateTime.Now;
            double millisecs = (end - start).TotalMilliseconds;
            Console.WriteLine("Query " + i + " = " + millisecs + "ms (" + millisecs / 1000 + "s)");

            start = DateTime.Now;
            order.Note = start.ToLongTimeString();
            context.SaveChanges();
            end = DateTime.Now;
            millisecs = (end - start).TotalMilliseconds;
            Console.WriteLine("SaveChanges " + i + " = " + millisecs + "ms (" + millisecs / 1000 + "s)");

            Thread.Sleep(1000);
        }

        Console.ReadKey();
    }

Please do not comment on my code - unless it is an invalid test ;)

The results are:

Query 1 = 3999.2288ms (3.9992288s)
SaveChanges 1 = 3391.194ms (3.391194s)

Query 2 = 18.001ms (0.018001s)
SaveChanges 2 = 4.0002ms (0.0040002s)

Query 3 = 14.0008ms (0.0140008s)
SaveChanges 3 = 3.0002ms (0.0030002s)

Query 4 = 13.0008ms (0.0130008s)
SaveChanges 4 = 3.0002ms (0.0030002s)

Query 5 = 10.0005ms (0.0100005s)
SaveChanges 5 = 3.0002ms (0.0030002s)

The first query takes time which I assume is the view generation? Or db connection?

The first save takes nearly 4 seconds which for the more complex save in my app takes over 20 seconds which is not acceptable.

Not sure where to go with this now :-(

UPDATE...

SQL Profiler shows first query and update are fast and are not different for first. So I know delay is Entity Framework as suspected.


Solution

  • It might not be the SaveChanges call - the first time you make any call to the database in EF, it has to do some initial code generation from the metadata. You can pre-generate this though at compile-time: http://msdn.microsoft.com/en-us/library/bb896240.aspx

    I would be surprised if that's the only problem, but it might help.

    Also have a look here: http://msdn.microsoft.com/en-us/library/cc853327.aspx