Skip to content

Instantly share code, notes, and snippets.

@bhameyie
Created May 28, 2013 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhameyie/5664001 to your computer and use it in GitHub Desktop.
Save bhameyie/5664001 to your computer and use it in GitHub Desktop.
linq func
In my mapping class, the method signature would be similar to this:
public abstract class FluentMap<TEntity> {
protected MyMapStuff Map(Expression<Func<TEntity, object>> propertyExpression){
return this;
}
}
My Expression takes func where TEntity is a class such as ‘MyEntity’, and the return type is object, thus covering all various returns value seeing as every class inherit from System.Object.
Now, to extract the information I may need out of that expresion, I can use
private PropertyPart ExtractMemberInfo(Expression<Func<TEntity, object>> propertyExpression)
{
var memberExpression = propertyExpression.Body as MemberExpression;
if (memberExpression != null)
{
return new PropertyMapInfo
{
Name = propertyExpression.Name,
ReflectedType = memberExpression.Member.ReflectedType,
PropertyType = memberExpression.Type
};
}
throw new ArgumentException(string.Format("In the expression {0}, \"{1}\" is not property of the entity", propertyExpression, propertyExpression.Name));
}
class PropertyMapInfo
{
public string Name { get; set; }
public Type ReflectedType { get; set; }
public Type PropertyType { get; set; }
}
Now I can do:
public class MyEntityMap: FluentMap<MyEntity>{
public MyEntityMap(){
Map(e=> e.Name);
}
}
Inside my ‘Map’ method, I can implement the appropriate ORM logic.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment