Posts

Showing posts from February, 2020

Generic query with NHibernate with eager loading

In my previous post, I showed how we could create generic methods to perform query,  https://csharptipstricks.blogspot.com/2019/12/usage-of-expression-to-create-generic.html . However, the methods present there does not allow eager loading. In case you are wondering how eager loading is performed, see below. Do know that there are ways to assign eager loading during mapping, but I will not show it in this post. Method I : SessionFactory.OpenSession().Query<MyEntity>().Fetch(x => x.Property1).Fetch(x => x.Property2).ToList(); Method II : var tempMyEntityQuery = GetSession().Query<MyEntity>().Fetch(x => x.Property1).ToFuture(); GetSession().Query<MyEntity>().Fetch(x => x.Property2).ToFuture(); List<MyEntity> myEntityList = tempMyEntityQuery .ToList(); Both the methods above will eager load Property1 & Property2 in a single trip to the database. However, I would choose method I because a single statement (with left outer join) is gener

The use of trigger to simplify the population of timestamp during update (PostgreSQL)

Often in development, we will want to include Created and Updated columns in each of our table, for tracking and recording purpose. However, if you are like me, we cannot avoid interacting with the database outside of our code, be it we want to insert or update a record manually. In case of PostgreSQL database, we can use function and trigger to track a particular column in a table. The function is for us to ensure that there is a new value for the Updated column, but we would not want to override a value is one is provided, we just want to ensure the Updated  column is up-to-date, just in case none is provided. Firstly, we need to create a function to provide a new value for the Updated column, if one is not given. CREATE OR REPLACE FUNCTION UPDATED_CHANGED ( ) RETURNS TRIGGER AS $$ begin IF NEW . UPDATED < = OLD . UPDATED THEN NEW . UPDATED : = NOW ( ) AT TIME ZONE 'UTC' ; END IF ; RETURN NEW ; END ; $$ LANGUAGE plpgsql ; Here, we are