Skip to content

Instantly share code, notes, and snippets.

@markryd
Created February 17, 2014 00:20
Show Gist options
  • Select an option

  • Save markryd/9042603 to your computer and use it in GitHub Desktop.

Select an option

Save markryd/9042603 to your computer and use it in GitHub Desktop.
Mapping from the domain with expressions and function composition
void Main()
{
var h = Compose(Domain.ToContract, Herp.FromContract);
var mapped = Contacts.Select(h);
mapped.Dump();
}
public class Domain
{
//maintain a mapping to our public contract classes
public static Expression<Func<Contacts, Contract>> ToContract {get { return c => new Contract{FirstContract = c.FirstName, LastContract = c.LastName, CompanyContact = c.Organization, Title = c.Title};}}
}
public class Contract
{
public string FirstContract {get;set;}
public string LastContract {get;set;}
public string CompanyContact {get;set;}
public string Title {get;set;}
}
public class Herp
{
public string FirstHerp {get;set;}
public string LastHerp {get;set;}
public static Expression<Func<Contract, Herp>> FromContract {get { return c => new Herp{FirstHerp = c.FirstContract, LastHerp = c.LastContract};}}
}
static Expression<Func<A, C>> Compose<A, B, C>(Expression<Func<A, B>> f, Expression<Func<B, C>> g)
{
var x = Expression.Parameter(typeof(A));
return Expression.Lambda<Func<A, C>>(Expression.Invoke(g, Expression.Invoke(f, x)), x);
}
@markryd

markryd commented Feb 17, 2014

Copy link
Copy Markdown
Author

We have a Contact in our domain but we want to be free to change that while not changing the public interface we publish to external developers. So we have a Contract class, then maintain an expression that maps from our domain to the contract class. Then external dev have whatever they need, and an expression to map from the contract to their class. By composing the two expressions and handing it off to EF we still get efficient retrieval. IE, in this case the generated SQL looks like

SELECT [t0].[FirstName] AS [FirstHerp], [t0].[LastName] AS [LastHerp] FROM [Contacts] AS [t0]

even though we have the entire thing mapped in our contract expression.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment