DirectSaver

DirectSaver  can be used for quick data insert and update bypassing Entity Framework time consuming operations. In order to use it follow steps below:

  1. Inherit your DataContext class from ShamanDbContext instead of DbContext, and set necessary options in constructor. For example

    ShamanDbContext  provides GetDirectSaver  method that is factory method for DirectSaver objects.
  2. Obrain direct saver object related for entity type
  3. Use Insert or Update method depending on situation, i.e.

Supported features

  1. Works only with MsSql Server, but can be extended for other databases when necessary.
  2. Identity fields and other fields marked with DatabaseGeneratedAttribute are readed back from database after insert operation.

Demo

Direct saver has been tested with small program for data migration. Data from XML file was persisted in MsSQL database.

Option 1, classic Ef usage

At the beginning I’ve used simple code template:

I’ve spend some time for optimizing performance but finally gave up. I was totally disappointed obtaining speed between 15-40 saved elements per second. My biggest dataset consists of 105.000 records so estimated time was around hour.

ds-01

Option 2, DirectSaver

I’ve replaced context.RecipeNodes.Add and context.SaveChanges() with Insert and Update, so my code template looks now like this.

Performance was quite good, between 1600 and 2400 records per second.

ds-02

Conclusion

DirectSaver can be used for mass data insert or update with great performance and without effort related to using SqlCommand. Exactly the same, simple code can be used after model migration, because DirectSaver uses ‘code first’ annotation for obtaining data model.
Disadvantage of this approach is that programmer must care about data relational consistency and object changes detection by himself.