Monday, July 27, 2015

LINQ Eager and Lazy Loading


Here's a little bit on using Linq and the ways to get data out via Eager / Lazy loading and LINQ methods vs operators. The explanations are in the code comments below.

using System.Data.Entity;
using System.Linq;
using EFFundamental;

namespace ConsoleApplication1
{
    class Program
    {
        // How to query against entity data model
        static void Main(string[] args)
        {
            LinqOperatorLazyLoading();
            LinqOperatorEagerLoading();
            LinqMethods();
            ProjectionQuery();
        }

        // using LINQ operator
        // Lazy loading = fetch only main data and have to make subsequent calls to get related data. 
        // Use when you know related data is not required at all or at the time of the call. 
        private static void LinqOperatorLazyLoading()
        {
            var context = new CHEntities();
            var query = from c in context.council_member 
                        where c.end_dtm != null
                        select c;
            
            var result = query.ToList();

           // note Lazy loading is by default, on.  If you want to change this..
           // context.ContextOptions.LazyLoadingEnabled = false;
        }

        // using LINQ operator
        // Eager loading = explicitly fetching all the data related in one call.
        // Good if all your stuff is not too large or you are unsure of what pieces of data you will need. 
        // If it is a large amount of data.. slower but more complete. 
        private static void LinqOperatorEagerLoading()
        {
            var context = new CHEntities();
            var query = from c in context.council_member.Include("address") // the .Include is what makes it Eager loading (these are the "extra" objects )
                                                        .Include(x => x.council_lku) // to use lambdas, make sure to add: using System.Data.Entity;
                        where c.end_dtm != null
                        select c;
            
            var result = query.FirstOrDefault();
        }

        // using LINQ methods .WHERE etc.. 
        private static void LinqMethods()
        {
            var context = new CHEntities();
            var result = context.Compliance_Notes.Where(x => x.last_updated_by == "ctenn").ToList();
        }

        private static void ProjectionQuery()
        {
            var context = new CHEntities();
            var query = from c in context.council_member.Include("address")
                        where c.end_dtm != null
                        // anonymous type and 2 of its properties. new object selecting only the properties you want. 
                        select new
                        {
                            c.branch, 
                            c.end_dtm
                        };
        }
    }
}