Thursday, May 21, 2015

Implementing a Base Class with Entity Framework

I want to add a bunch of audit fields to all of my tables.  Here's how I did it with a base class.  Note that the base class must have a key column. The subclass does not have an ID explicitly; it inherits the ID column from the base class.

The call to MapInheritedProperties will put the inherited properties directly on the subclass table. 

Nhibernate performance improvements

I recently took a process that was running for hours and would never finish and made it run in less than an hour.  It was also using one big transaction which was locking other people out of the database.  So here are the big 3 performance improvements I used.


I basically used some code from the NH documentation to implement SQL execution batching.  I also batched the transactions which was very easy to do.  You just do:


This was a huge performance boost.

Native SQL

There was some code that read a list of entities from the DB into a session and then updated the same field to the same value in a loop.  Instead I used "session.CreateQuery" to run a single update.  Then the code did not have to do the select, nor load all the entities into memory.


Running selects in a loop can be disastrous to performance.  So where possible I pre-fetched data that I needed before the loop and put it into a Dictionary.  (Or Map, Hash Table, whatever you want to call it!)