2013-03-14 63 views
0

我正在使用System.CodeDom生成代码。有人可以告诉我如何在构造函数中创建代码。如何生成构造函数和代码?

,我想输出:

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(); 
     } 
    } 

我所用的CodeDOM完成至今:

@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); 

任何想法?

回答

0

明白了:

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); 
} 
相关问题