0

I'm using System.CodeDom to generate code. Can someone please tell me how I would create the code within a constructor.

The output that I want:

internal class CurrencyMap : EntityTypeConfiguration<Currency>
    {
        public CurrencyMap()
        {
            ToTable("Currencies");
            HasKey(m => m.Id);
            Property(m => m.Name).IsRequired().HasMaxLength(100);
            Property(m => m.Code).IsRequired().HasMaxLength(10);
            Property(m => m.Symbol).HasMaxLength(10);
            Property(m => m.IsEnabled).IsRequired();
        }
    }

What I have done with CodeDom so far:

@class = new CodeTypeDeclaration(className + "Map");
            @class.IsClass = true;
            @class.Attributes = MemberAttributes.Public;
            @class.BaseTypes.Add(new CodeTypeReference
            {
                BaseType = string.Format("EntityTypeConfiguration`1[{0}]", className),
                Options = CodeTypeReferenceOptions.GenericTypeParameter
            });

            var constructor = new CodeConstructor();
            constructor.Attributes = MemberAttributes.Public;


            var sb = new StringBuilder();

            // TODO: iterate through each field here and create the Property(m=>..... statements, etc.
            foreach (var field in fields)
            {
                sb.Clear();
                //Im guessing I will have to build a string for the fluid stuff, right?
            }

            @class.Members.Add(constructor);

Any ideas?

svick
  • 236,525
  • 50
  • 385
  • 514
Matt
  • 6,787
  • 11
  • 65
  • 112

1 Answers1

0

Got it:

constructor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(),
    "ToTable", new CodeExpression[] { new CodePrimitiveExpression(tableName) }));

foreach (var field in fields)
{
    CodeExpression statement = new CodeMethodInvokeExpression(
        new CodeThisReferenceExpression(), "Property", new CodeExpression[] { new CodeSnippetExpression("m => m." + field.Name) });

    if (field.IsRequired)
    {
        statement = new CodeMethodInvokeExpression(statement, "IsRequired");
    }
    //etc: TODO...
    constructor.Statements.Add(statement);
}
Matt
  • 6,787
  • 11
  • 65
  • 112