On a project I am working on, we have lots of static data in our database that we load in via T4 templates. Ethnicity is an example of the static data we model and Ethnicites is an example of a static lookup class generated by a T4 template.
public class Ethnicity { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual double AverageHeight { get; set; } } public static class Ethnicities { public static Ethnicity Caucasian = new Ethnicity {Id = 1, Name = "Caucasian", AverageHeight = 5.8}; public static Ethnicity Asian = new Ethnicity { Id = 2, Name = "Asian", AverageHeight = 5.7 }; public static IDictionary<int, Ethnicity> EthnicityById = new Dictionary<int, Ethnicity> { {1, Caucasian}, {2, Asian}}; }public class Person { public virtual int Id { get; set; } public virtual Ethnicity Ethnicity { get; set; } }
When I retrieve a person from the database, I would like the person's Ethnicity to be retrieved from Ethnicities.EthnicityById if exists else it should do whatever Nhibernate does by default. If Ethnicity is retrieved from Ethnicities.EthnicityById then all of its data can be loaded at once which avoids another call to the database. From what I've read, I think implementing a ICompositeUserType for Ethnicity would be a way to accomplish this. Does this sound like a valid approach? If it does, then could someone steer me in the right direction in implementing ICompositeUserType?
I was originally thinking about using Second Level Cache for this problem but I couldn't figure out how to load the entire table (all of the entities) into the cache.
Easiest way would be to change the responsibility of loading Ethnicities to your static class (or more preferably a non-static class that is injected as a dependency when you need it). Have a GetById method that first checks the dictionary, then falls back to loading from the database.
Or you could try the second level cache again. If the class is mapped to be cacheable (via the <cache …/> tag), all you have to do is call something like nhSession.QueryOver<Ethnicity>().List() once at the start of your application. That should cache each Ethnicity entity and prevent future db hits.
--
You received this message because you are subscribed to the Google Groups "nhusers" group.
To view this discussion on the web visit https://groups.google.com/d/msg/nhusers/-/9tWmdg5oGB8J.
To post to this group, send email to nhu...@googlegroups.com.
To unsubscribe from this group, send email to nhusers+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/nhusers?hl=en.