Creating Entity Classes Using CodeDom

CodeDom namespace is simply amazing, it lets you to write language specific code. I was just mingling with CodeDom namespace and though why not create Entity Classes which maps to the database table. So I put together this small piece of code which creates the entity class. All the data in the example below is constant but I am sure that you get the idea.

Here is my Code Generator:

using System;
using System.Data;
using System.Configuration;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Text;
using System.IO;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using System.Reflection.Emit;

namespace CodeDomTesting
{
    
public class MyCodeGenerator
    {

        
private CodeNamespace currentNameSpace;
        
private CodeTypeDeclaration currentClass; 

        
public MyCodeGenerator()
        {
            
this.currentNameSpace = InitializeNameSpace("AzamSharpCodeGenerator");
            
this.currentClass = CreateClass("MyFirstClass");
            CreateFields(
this.currentClass); 
        }


        
private CodeNamespace InitializeNameSpace(string name)
        {
            CodeNamespace currentNameSpace = 
new CodeNamespace(name);
            currentNameSpace.Imports.Add(
new CodeNamespaceImport("System"));
            currentNameSpace.Imports.Add(
new CodeNamespaceImport("System.Text"));

            
return currentNameSpace; 
        }

        
private CodeTypeDeclaration CreateClass(string name)
        {
            CodeTypeDeclaration ctd = 
new CodeTypeDeclaration(name);          

            ctd.IsClass = 
true;
            ctd.Attributes = MemberAttributes.Public;
            
            
return ctd; 
        }

        
private void CreateFields(CodeTypeDeclaration ctd)
        {

            DataSet ds = DatabaseHelper.GetDataSet();          
            
            
foreach (DataColumn dc in ds.Tables[0].Columns)
            {
                ctd.Members.Add(
new CodeMemberField(dc.DataType.ToString()
                ,FormatFieldNameFromColumnName(dc.ColumnName)));

                CodeMemberProperty property = 
new CodeMemberProperty();
                property.Name = dc.ColumnName;
                property.Type = 
new CodeTypeReference(dc.DataType);
                property.HasGet = 
true;
                property.HasSet = 
true;
                property.GetStatements.Add(
new CodeMethodReturnStatement(
                                   
new CodeFieldReferenceExpression(
                                     
new CodeThisReferenceExpression(),
                                  FormatFieldNameFromColumnName
                                  (dc.ColumnName))));

                property.SetStatements.Add(
new CodeAssignStatement(
                                   
new CodeFieldReferenceExpression(
                                     
new CodeThisReferenceExpression(),
                                     FormatFieldNameFromColumnName
                                     (dc.ColumnName)),
                                     
new                                     
                                     
CodePropertySetValueReferenceExpression()));
                      
                 ctd.Members.Add(property); 
            }


        }

        

        
// make the first letter to be the lower case 
        
private string FormatFieldNameFromColumnName(string columnName)
        {
            
return columnName.Replace(columnName[0].ToString(),
            columnName[0].ToString().ToLower());
        }

        
public string GenerateCode()
        {

           CodeGeneratorOptions options = 
new CodeGeneratorOptions();
            options.BracingStyle = "C";
            options.IndentString = "  ";

            StringBuilder sbCode = 
new StringBuilder();
            StringWriter sw = 
new StringWriter(sbCode);

            
this.currentNameSpace.Types.Add(this.currentClass); 

            CSharpCodeProvider provider = 
new CSharpCodeProvider();
            provider.GenerateCodeFromNamespace(
this.currentNameSpace,
                sw, options);                 
            

            
return sbCode.ToString();
       }                 
       
    } 
}

 

And Here is the database helper class:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.CodeDom; 

namespace CodeDomTesting
{
    
public class DatabaseHelper
    {
        
public static DataSet GetDataSet() 
        {
            
string connectionString = @"Server=localhost;Database=
            School;Trusted_Connection=true";
            SqlConnection myConnection = 
new SqlConnection(connectionString);
            SqlDataAdapter ad = 
new SqlDataAdapter("SELECT * FROM Users"
            , myConnection);
            DataSet ds = 
new DataSet();
            ad.FillSchema(ds, SchemaType.Mapped,"Users");
            
            
return ds;             
        }

    }
}

Here is the main method:

 MyCodeGenerator code = new MyCodeGenerator();
           
string theCode = code.GenerateCode();

           
string path = @"C:\User.cs";
           StreamWriter sw = 
new StreamWriter(path);
           sw.Write(theCode);

           sw.Close();           

And if you are wondering that does User.cs file contain well after you run the generator it will write the field name and make the properties. Check out the automatically generated User.cs file below:

namespace AzamSharpCodeGenerator
{
  
using System;
  
using System.Text;
  
  
  
public class MyFirstClass
  {
    
    
private int userID;
    
    
private string firstName;
    
    
private string lastName;
    
    
private string address;
    
    
private int noOfPets;
    
    
private int UserID
    {
      
get
      
{
        
return this.userID;
      }
      
set
      
{
        
this.userID = value;
      }
    }
    
    
private string FirstName
    {
      
get
      
{
        
return this.firstName;
      }
      
set
      
{
        
this.firstName = value;
      }
    }
    
    
private string LastName
    {
      
get
      
{
        
return this.lastName;
      }
      
set
      
{
        
this.lastName = value;
      }
    }
    
    
private string Address
    {
      
get
      
{
        
return this.address;
      }
      
set
      
{
        
this.address = value;
      }
    }
    
    
private int NoOfPets
    {
      
get
      
{
        
return this.noOfPets;
      }
      
set
      
{
        
this.noOfPets = value;
      }
    }
  }
}

Enjoy!

 by IMHO 1.3

Print | posted @ Wednesday, June 14, 2006 7:06 PM

Twitter