Hi,
I have this code for generating a class.
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);
}
}
}
}
I call it like this :
GenClass objGenClass = new GenClass("Folio2");
objGenClass.AddColumns();
objGenClass.CreateCS(@"../../Models/Folio2.cs");
It has generated this code :
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;
}
}
How can I add the [Key] attribute above the field and also how to designate the field as IDENTITY ?
Im looking for this output :
[Key]
public int Refno {get; set;}
Please suggest. Thank you in advance.
What I have tried:
Tried doing it as in
this Link but it is not working for Primary key attribute.
Tried adding the KeyAttribute through CustomAttributes.Add. Didn't work.
Also Tried :
CodeAttributeDeclaration mattr = new CodeAttributeDeclaration("Key");
CodeMemberField mfield0 = new CodeMemberField(typeof(Int32), "RefNo");
mfield0.CustomAttributes.Add(mattr);
It resulted in :
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
{
[Key()]
public int RefNo;
}
}