Created
January 10, 2012 01:31
-
-
Save masaru-b-cl/1586237 to your computer and use it in GitHub Desktop.
EF type-safe include
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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