1

In Entity framework 6, when running the overload of the Include method that uses lambda expression to the context:

Context.SomeEntity.Include(x => x.MyOtherEntity))

it returns an IQueryable, whereas when we use the one that uses string:

Context.SomeEntity.Include("MyOtherEntity")

it returns a DbQuery.

I need to return a DbQuery and don't want to use the string overload so that I can get inclusion errors at compile time.

How can I return a DbQuery after using the include with the lambda?

1
  • Why do you need DbQuery? Why do you not use the other overload then. You could use a custom method to pass in your Expression (x => x.MyOtherEntity) and build the string for it up manually. There are lots of those to find on SO
    – user604613
    May 21, 2015 at 10:10

1 Answer 1

0

I believe you can't convert an IQueryable to a DbQuery. However, you can use this code to pass in an expression and get the required string.

Be sure to write some unit tests for this and adapt the method for your needs. I have not tested it properly yet.

public static string GetMemberName<T>(this Expression<Func<T>> expression)
    {
        MemberExpression memberExp;
        if (!TryFindMemberExpression(expression.Body, out memberExp))
            return string.Empty;

        var memberNames = new Stack<string>();
        do
        {
            memberNames.Push(memberExp.Member.Name);
        }
        while (TryFindMemberExpression(memberExp.Expression, out memberExp));

        return string.Join(".", memberNames.ToArray());
    }


private static bool TryFindMemberExpression(Expression exp, out MemberExpression memberExp)
    {
        memberExp = exp as MemberExpression;
        if (memberExp != null)
        {
            return true;
        }

        if (IsConversion(exp) && exp is UnaryExpression)
        {
            memberExp = ((UnaryExpression)exp).Operand as MemberExpression;
            if (memberExp != null)
            {
                return true;
            }
        }

        return false;
    }

    private static bool IsConversion(Expression exp)
    {
        return (exp.NodeType == ExpressionType.Convert || exp.NodeType == ExpressionType.ConvertChecked);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.