Search code examples
c#objectexpressionbuilder

ExpressionBuilder return any type of object


The code below works fine for primitive expressions (no surprise there)

public class SiteContextExpressionBuilder : ExpressionBuilder {
   public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {
      PropertyInfo property = typeof(SiteContext).GetProperty(entry.Expression);
      return new CodePrimitiveExpression(property.GetValue(null, null)));
   }
}

Now I would like to return non primitive types as well. Let's say a Company object.
How does that work? I can't seem to find any good examples.

Invalid Primitive Type: ... Consider using CodeObjectCreateExpression

How do I implement the CodeObjectCreateExpression or alternative?


Solution

  • I don't know what the constructor for your Company object looks like, so here's an example with Size:

    Constructor

    new Size(640, 400)
    

    With CodeObjectCreateExpression

    CodeExpression newSizeExpr = new CodeObjectCreateExpression(new CodeTypeReference(“System.Drawing.Size”),
       new CodePrimitiveExpression(640), new CodePrimitiveExpression(400));
    

    If your Company constructor accepts primitive arguments, you can just use CodePrimitiveExpressions as in the above example. If it requires non primitive types, you can instantiate those non-primitive types with CodePrimitiveExpressions. Recurse until you have what you need to construct your Company object.

    Update: Source may be helpful: http://blogs.msdn.com/bclteam/archive/2006/04/10/571096.aspx