Use Reflection and Expression to Find an Entity by Primary Key

On occasion I maintain a project based on Entity Framework Database First approach.  This project is using ObjectContext.  I was recently working on a generic feature that was requiring me to find an entity based on primary key. In order to do this I have to dynamically create a where clause that filders data based on ID, since ObjectContext API does not support Find method.  As part of the solution, I need to create a method that returns Expression<Func<T, bool>> , which I will dynamically pass into a method that operates on an object set.  I am not going to describe other methods, as they are less interesting.  I do however want to show how to dynamically create Expression<Func<T, bool>>.  I put comments in line, so that you can see what is going on.

        /// <summary>
        /// Create expression for .Where(entity => entity.Id == 'id')
        /// </summary>
        /// <typeparam name="T">Type of entity</typeparam>
        /// <param name="id">Entity ID</param>
        /// <returns></returns>
        private static Expression<Func<T, bool>> GetExpression<T>(object id)
        {
            // Find primary key property based on primary key attribute.
            var keyProperty = typeof(T).GetProperties().
                First(
                    one =>
                    one.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), true)
                    .Any(two => ((EdmScalarPropertyAttribute)two).EntityKeyProperty));

            // Create entity => portion of lambda expression
            ParameterExpression parameter = Expression.Parameter(typeof(T), "entity");

            // create entity.Id portion of lambda expression
            MemberExpression property = Expression.Property(parameter, keyProperty.Name);

            // create 'id' portion of lambda expression
            var equalsTo = Expression.Constant(id);

            // create entity.Id == 'id' portion of lambda expression
            var equality = Expression.Equal(property, equalsTo);

            // finally create entire expression - entity => entity.Id == 'id'
            Expression<Func<T, bool>> retVal = 
                Expression.Lambda<Func<T, bool>>(equality, new[] { parameter });
            return retVal;
        }

Enjoy.