Governor Technology Blog

16 February 2010 by Cameron Morrison

EntityFramework include multiple extension method

When using the Entity Framework you often find that you need to include data not loaded by default from related objects in queries.  To do this you use the ObjectQuery<T>.Include Method, the method supports chaining so that you can include multiple relationships in a single statement, eg.

context.Nomination.Include("Award").Include("Votes")

However, this can get very cumbersome if you need to fetch data from a number of different relationships, eg.

context.Nomination.Include("Award")
                  .Include("Nominee")
                  .Include("Nominator")
                  .Include("Media")
                  .Include("Media.MediaType")
                  .Include("Votes")
                  .Include("Support")
                  .Include("Support.User")

Although that snippet looks managable when displayed on it's own, you often use the Include method in LINQ statements, where it can get pretty silly.

Here is an extension method you can use to tame this a little, it adds some syntatic sugar to the Include to allow a params argument, which makes using it easier.

Listing 1: Iterative style.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;

namespace GovernorTechnology
{
    public static class ObjectQueryExtender
    {
        public static ObjectQuery Include(this ObjectQuery target, params string[] paths)
        {
            if (paths.Count() >= 1)
            {
                ObjectQuery query = target.Include(paths.First());
                
                foreach (string path in paths.Skip(1))
                {
                    query = query.Include(path);
                }

                return query;
            }
            else
            {
                return target;
            }
        }
    }
}

Listing 2: Recursive style.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;

namespace GovernorTechnology
{
    public static class ObjectQueryExtender
    {
        public static ObjectQuery Include(this ObjectQuery target, params string[] paths)
        {
            if (paths.Count() >= 1)
            {
                return target.Include(paths.First()).Include(paths.Skip(1).ToArray());
            }
            else
            {
                return target;
            }
        }
    }
}

Example usage.

context.Nomination.Include("Award", "Votes")

Both of these do the same thing, it's up to you which one you use depending on the style you prefer.

0 comment(s) for “EntityFramework include multiple extension method”


    Leave comment:


    (not shown)


    (optional - remember http://)