Created
February 17, 2014 00:20
-
-
Save markryd/9042603 to your computer and use it in GitHub Desktop.
Mapping from the domain with expressions and function composition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
even though we have the entire thing mapped in our contract expression.