Showing posts with label Lambda Expressions. Show all posts
Showing posts with label Lambda Expressions. Show all posts

Saturday, October 24, 2009

Strongly Typed Programming by Lambda Expressions

public class StrongTypedHelper
{
    public static string GetPropertyOrFieldName<T>(Expression<Func<T, object>> lambdaExpression)
    {
        MemberExpression memberExpression = lambdaExpression.Body as MemberExpression;
        if (memberExpression == null)
        {
            UnaryExpression unaryExpression = lambdaExpression.Body as UnaryExpression;
            if (unaryExpression != null)
            {
                memberExpression = unaryExpression.Operand as MemberExpression;
            }
        }

        Debug.Assert(memberExpression == null, "This expression is not supported.");
        MemberExpressionexpression = memberExpression.Expression as MemberExpression;
        if (expression == null)
        {
            return memberExpression.Member.Name;
        }
        else
        {
            string memberName = null;
            do
            {
                memberName = String.Format("{0}.{1}", expression.Member.Name, memberName);
                expression = expression.Expression as MemberExpression;
            } while (expression != null);

            return memberName + memberExpression.Member.Name;
        }
    }
}

Use this helper class we can use strongly typed instead of hard coded strings in UI data binding or ObjectQury.Include mehtod, and other places. Ex.

Instead of: context.Orders.Include(“OrderDetails”).Where(x => x.OrderId = 123).FirstOrDefault();

Now we use use: context.Orders.Include(StrongTypedHelper<Order>.GetPropertyOrFieldName(x => x.OrderDetails).Where(x => x.OrderId = 123).FirstOrDefault();