News + Views

EntityFramework Include Multiple Extension Method

Posted by | Tuesday, February 16, 2010 | not categorized | Leave comment

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.

Not tagged

 

Leave a Comment

Your name *

Your e-mail address *

Your Message *

Archive

2012    (2)

2011    (19)

2010    (16)

2009    (10)

 
 

Contact Us

 

Governor Technology Limited
91-93 Southwark Street
LondonSE1 0HX
Tel:020 7593 2210
Fax: 020 7620 6172
Email: info@governor.co.uk