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

有任何想法吗?

4

1 回答 1

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);
}
于 2013-03-14T16:14:28.490 回答