using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq.Expressions;
using System.Reflection;
namespace Test.DataAccess
{
///
/// See http://msmvps.com/blogs/matthieu/archive/2008/06/06/entity-framework-include-with-func-next.aspx
///
public static class ObjectQueryExtension
{
public static ObjectQuery Include(this ObjectQuery mainQuery, Expression> subSelector)
{
return mainQuery.Include(FuncToString(subSelector.Body));
}
private static string FuncToString(Expression selector)
{
switch (selector.NodeType)
{
case ExpressionType.MemberAccess:
return ((selector as MemberExpression).Member as PropertyInfo).Name;
case ExpressionType.Call:
var method = selector as MethodCallExpression;
return FuncToString(method.Arguments[0]) + "." + FuncToString(method.Arguments[1]);
case ExpressionType.Quote:
return FuncToString(((selector as UnaryExpression).Operand as LambdaExpression).Body);
}
throw new InvalidOperationException();
}
public static K Include(this EntityCollection mainQuery, Expression> subSelector)
where T : EntityObject, IEntityWithRelationships
where K : class
{
return null;
}
public static K Include(this T mainQuery, Expression> subSelector)
where T : EntityObject
where K : class
{
return null;
}
}
}
// I'm getting a very strange compilation error because of extension methods.
// "Missing compiler required member 'System.Runtime.CompilerServices.ExtensionAttribute..ctor'"
// http://stackoverflow.com/questions/205644/error-when-using-extension-methods-in-c
// This seems to fix it...
// Sometimes it works without it (which is why you may see it commented out here...)
namespace System.Runtime.CompilerServices
{
public class ExtensionAttribute : Attribute { }
}