The Pragmatic Programmer

Tulisan iseng kalo ada waktu.
See also: Other Geeks@INDC

How to Write Your Own Code Generator - Part I

If you are a business application developer and you're writing you're application using entity paradigm that is you are using object/class to represents your database tables then I am absolutely sure that you had been writing this type of code many times:

public class Person
{
private string _name;
public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
private DateTime _dateOfBirth;
public DateTime DateOfBirth
    {
        get { return _dateOfBirth; }
        set { _dateOfBirth = value; }
    }
// etc..
}

Unless you have written your own code generator or any other third party tools to automatically generate the code for you based on your database design then this article is for you.

In this Part I, I will only cover the theory not the implementation. I hope the reader will understand how to make one and write their own implementation but I'll wrote the implementation in the Part II.

The Theory
OK, here is the theory:

All you have to do is just find a way to read all the tables (including the views if you wish) contains in the database that you want to generate the code. Create a class to handle the code generation for a table. You have to map the sql data type with the equivalent .Net data type. Generate the code for each tables by passing it to your table class generator.

So, what you have to do is:
1. Find a way to read all the tables. There are many ways to solve this.
2. Create a class which responsible to generate the code for a table. If you do this, you have divide your problem into a smaller problem and it will be easier for you to conquer the problem.
3. Map the sql data type to .Net equivalents. This is up to you but you can find the reference table in MSDN.

Conclusion
OK, that's it. There is a third party scripting tools like CodeSmith that already handled the point 1 but you have to learn how to use it first :). Like I said I'll just covered the theory for now and its up to you to implement it. If you have any questions, you can put it on the comments box.

Share this post: | | | |

Comments

csharpindonesia said:

I use SMO to handle the first point. The namespace is great.

# August 6, 2007 11:35 AM

norman said:

In C# 3.0, there's something handy about properties that may help you reduce the amount of code to type or code gen: http://geeks.netindonesia.net/blogs/norman/archive/2007/08/13/Auto_2D00_Implemented-Properties.aspx

:)

But, there are limitations though... no attributes.. :)

# August 13, 2007 3:31 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 
Are you human?:  


Enter the numbers above: