SetCustomAction in LinQ2NH to solve N+1 problem

Doing this in Criteria is easy, but in LinQ2NH is difficult but possible, the latter is just too new and too weak, hope the ugly string can be removed in the future.

    public class OrderRepository
        public IList<Order> GetOrdersWith(DateTime start
            , DateTime end)
            IList<Order> orders= new List<Order>();
            using (ISession session = NHibernateSessionManager.OpenSession())
                var queryable = session.Linq<Order>();
                // Option A:
                queryable.QueryOptions.RegisterCustomAction(c => c.SetFetchMode("OrderLineItems", FetchMode.Eager));
                // Option B:
                // queryable.Expand("OrderLineItems");
                orders = (queryable.Where(order => order.PlacedOn > start)
                    .Where(order => order.PlacedOn < end)
                    .Select(x => x)

                // This line will cause N+1 problem if fetch mode is not set to eager mode.

            return orders;

Note: NH3 will come with strongly type style, e.g.:
session.Query<Customer>().Fetch(c => c.Orders).ToList();


One thought on “SetCustomAction in LinQ2NH to solve N+1 problem

  1. String can be avoided by using a lambda expression and parsing it’s tree.. NCommon’s repository (among others) use this technique

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s