...Our test was to add a single, uninitialized instance of the class
to the database. Using DbContext.Add...
Did you make sure that your Code-First model is created and loaded into memory before you've called Add? I mean the following: If you use a test code like this ...
using (var context = new MyContext())
{
var myHugeBusinessObject = CreateItSomeHow();
context.HugeBusinessObjects.Add(myHugeBusinessObject);
context.SaveChanges();
}
... and it's the first time that you are using the context in your test application Add will actually spent some time to build the EF model in memory before it starts to add the object to the context.
You can separate these two steps simply by adding a dummy method before calling Add, for instance something like:
context.HugeBusinessObjects.Count();
I've built a test:
public class MyClass
{
public int Id { get; set; }
public string P1 { get; set; }
// ... P2 to P49
public string P50 { get; set; }
public MyClass Child1 { get; set; }
// ... Child1 to Child26
public MyClass Child27 { get; set; }
}
With this I created an object:
var my = new MyClass();
MyClass child = my;
for (int i = 0; i < 100; i++)
{
child.Child1 = new MyClass();
child = child.Child1;
}
child = my;
for (int i = 0; i < 100; i++)
{
child.Child2 = new MyClass();
child = child.Child2;
}
// and so on up to Child27
So this object graph has 2700 child objects with 50 scalar properties each. Then I tested this code:
using (var context = new MyContext())
{
var my = CreateWithTheCodeAbove();
context.MyClassSet.Count();
context.MyClassSet.Add(my);
context.SaveChanges();
}
...Count() (= building the EF model) needs roughly 25 seconds. Add needs 1 second. (Changing 100 to 1000 in the loops above (having then 27000 objects in the graph) increases the time for Add almost linearly to 9-10 seconds.) This result is independent of setting AutoDetectChangesEnabled to true or false.)
The next interesting result: If I add 20 navigation properties more (Child28 to Child47) to MyClass the time spent with building the model (Count() in the example code) explodes to 140 seconds. The duration of Add only increases linearly with the additional properties.
So, my hypothesis is: You are not actually measuring the time to add your business object to the context but the time EF needs to build the EF model in memory. The time to build the model seems to grow exponentially with the complexity of the model: Number of navigation properties on a class and perhaps also the number of different involved classes.
To separate these steps test with some dummy call like suggested above. If you already have this separation... omg, forget this post.
dbContext.Configuration.AutoDetectChangesEnabled = false;when you create the context and measure again. Since you sayAddis slow (and notSaveChanges, right?) I suspect that automatic change detection/snapshot creation makes things slow.AutoDetectChangesEnabledset tofalse. And yes, theAddwas the slow portion, andSaveChangesfinishes relatively quickly.