Skip to content

Instantly share code, notes, and snippets.

@masaru-b-cl
Created January 10, 2012 01:31
Show Gist options
  • Save masaru-b-cl/1586237 to your computer and use it in GitHub Desktop.
Save masaru-b-cl/1586237 to your computer and use it in GitHub Desktop.
EF type-safe include
using System;
using System.Data.Objects;
using System.Linq.Expressions;
namespace ConsoleApplication1
{
public static class DatabaseEntitiesExtensions
{
public static ObjectQuery<T> Include<T, V>(this ObjectQuery<T> entities, Expression<Func<T, V>> expression)
{
var memberExp = expression.Body as MemberExpression;
if (memberExp == null)
{
throw new ArgumentException();
}
var entityName = memberExp.Member.Name;
return entities.Include(entityName);
}
}
public class Program
{
static void Main(string[] args)
{
var context = new DatabaseEntities();
var persons = context.Persons.Include(x => x.Department);
foreach (var item in persons)
{
Console.WriteLine(item.PersonName + "," + item.Department.DepartmentName);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment