Skip to content

Instantly share code, notes, and snippets.

@jdaigle
Created September 8, 2010 12:34
Show Gist options
  • Save jdaigle/570066 to your computer and use it in GitHub Desktop.
Save jdaigle/570066 to your computer and use it in GitHub Desktop.
public static Expression<Func<TEntity, TReturn>> GetFieldExpression<TEntity, TReturn>(string fieldName)
{
var type = typeof(TEntity);
var member = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
.FirstOrDefault(x => x.Name == fieldName);
if (member == null)
throw new UnknownPropertyException(type, fieldName);
var param = Expression.Parameter(member.DeclaringType, "x");
Expression expression = Expression.Field(param, fieldName);
if (member.FieldType.IsValueType)
expression = Expression.Convert(expression, typeof(object));
return (Expression<Func<TEntity, TReturn>>)Expression.Lambda(typeof(Func<TEntity, TReturn>), expression, param);
}
public static Expression<Func<TEntity, object>> RevealField<TEntity>(this IMappingProvider classMap, string fieldName)
{
return GetFieldExpression<TEntity, object>(fieldName);
}
public static Expression<Func<TEntity, TReturn>> RevealField<TEntity, TReturn>(this IMappingProvider classMap, string fieldName)
{
return GetFieldExpression<TEntity, TReturn>(fieldName);
}
public static PropertyPart MapField<TEntity>(this ClasslikeMapBase<TEntity> classMap, string fieldName)
{
return classMap.Map(GetFieldExpression<TEntity, object>(fieldName)).Access.Field();
}
public static IdentityPart MapIdField<TEntity>(this ClassMap<TEntity> classMap, string fieldName)
{
return classMap.Id(GetFieldExpression<TEntity, object>(fieldName)).Access.Field();
}
public static ComponentPart<TComponent> MapComponentField<TEntity, TComponent>(this ClassMap<TEntity> classMap, string fieldName, Action<ComponentPart<TComponent>> action)
{
return classMap.Component<TComponent>(GetFieldExpression<TEntity, TComponent>(fieldName), action).Access.Field();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment