Include
Type-safe Include: a completely type-safe way to include nested objects in scenarios with DomainServices and RIA in, for example, Silverlight applications. Example: Include(x=>x.Parent) instead of Include("Parent"). A more detailed explanation can be found at http://www.chrismeijers.com/post/Type-safe-Include-for-RIA-DomainServices.aspx
Source
using System.Linq.Expressions;
using System.Collections.Generic;
namespace System.Data.Objects
{
public static class SilverExtensions
{
public static ObjectQuery<T> Include<T, T2>(this ObjectQuery<T> data, Expression<Func<T, ICollection<T2>>> property1, Expression<Func<T2, object>> property2)
where T : class
where T2 : class
{
var name1 = (property1.Body as MemberExpression).Member.Name;
var name2 = (property2.Body as MemberExpression).Member.Name;
return data.Include(name1 + "." + name2);
}
public static ObjectQuery<T> Include<T, T2>(this ObjectQuery<T> data, Expression<Func<T, T2>> property1, Expression<Func<T2, object>> property2) where T : class
{
var name1 = (property1.Body as MemberExpression).Member.Name;
var name2 = (property2.Body as MemberExpression).Member.Name;
return data.Include(name1 + "." + name2);
}
public static ObjectQuery<T> Include<T>(this ObjectQuery<T> data, Expression<Func<T, object>> property) where T : class
{
var name = (property.Body as MemberExpression).Member.Name;
return data.Include(name);
}
}
}
Example
Instead of writing:
ObjectContext.Employee.Include("Address").Include("Department.Division");
one can now use a completely type-safe variant:
ObjectContext.Employee.Include(x=>x.Address).Include(y=>y.Department, z=>z.Division);
This finally gets rid of that nasty piece of untyping in an otherwise lovely type-safe system...
Author: Chris Meijers
Submitted on: 25 okt. 2010
Language: C#
Type: System.Data.Objects.ObjectQuery<T>
Views: 9151