context.Customer.Include("CustomerAddress")
There are a few drawbacks with this. First of all, it is not very refactor friend. Secondly there is no support from Intellisense.
It would be great if you can write like this:
context.Customer.Include(m => m.CustomerAddress)
Well, as it turns out it is not very hard to accomplish that. We can create a extension method also called Include for DbQuery class with some help from Expression class as bellow:
public static class QueryHelper { private static string GetPath<T>(Expression<Func<T, object>> memberExpression) { var bodyString = memberExpression.Body.ToString(); string path = bodyString.Remove(0, memberExpression.Parameters[0].Name.Length + 1); return path; } public static DbQuery<T> Include<T>(this DbQuery<T> query, Expression<Func<T, object>> memberExpression) { string includePath = GetPath<T>(memberExpression); return query.Include(includePath); } }
Hi this code is ok, but if I want to translate from more complex constructios like:
ReplyDeleteExpression> include =
p => p.Friends.Select(f => f.Car);
string strInclude = include.GetPath();
// the value of strInclude will be: Friends.Select(p => p.Car)
// but I would like it returns: Friends.Car
my question, Did anyone know how to do this?