如何在codeDOM生成的c#代码中获取[Key]属性

时间:2019-01-17 05:08:04

标签: c# entity-framework-6 codedom

我正在编写代码以为运行时表生成一个类文件,以将其包含在实体框架迁移中。

要在类文件中知道如何将CodeMemberFields指定为主键或IDENTITY等,

我有此代码:

    namespace EFCodeFirstTest
{
    class GenClass
    {
        CodeCompileUnit CompileUnit;
        CodeTypeDeclaration NewClass;

        public GenClass(String Classname)
        {
            CompileUnit = new CodeCompileUnit();
            CodeNamespace ns = new CodeNamespace("EFCodeFirstTest");
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel.DataAnnotations"));
            ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel.DataAnnotations.Schema"));
            ns.Imports.Add(new CodeNamespaceImport("System.Data.Entity.Spatial"));
            NewClass = new CodeTypeDeclaration(Classname);
            NewClass.IsClass = true;
            NewClass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
            ns.Types.Add(NewClass);
            CompileUnit.Namespaces.Add(ns);
        }

        public void AddColumns()
        {
            CodeMemberField mfield0 = new CodeMemberField(typeof(Int32), "RefNo");
            mfield0.Attributes = MemberAttributes.Public;
            mfield0.Type = new CodeTypeReference(typeof(Int32));
            NewClass.Members.Add(mfield0);
        }

        public void CreateCS(String mfilename)
        {
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BracingStyle = "C";
            options.BlankLinesBetweenMembers = false;
            using (StreamWriter sw = new StreamWriter(mfilename))
            {
                provider.GenerateCodeFromCompileUnit(CompileUnit, sw, options);
            }
        }
    }
}

我这样称呼它:

GenClass objGenClass = new GenClass("Folio2");
objGenClass.AddColumns();
objGenClass.CreateCS(@"../../Models/Folio2.cs");

输出:

namespace EFCodeFirstTest
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public sealed class Folio2
    {
        public int RefNo;
    }
}

我想获取参考号上方的[Key]属性。 我该怎么做 ?

0 个答案:

没有答案