greenoldman
greenoldman

Reputation: 21062

Code generation from external text template -- should I write regular C# tool or use text template tool?

I had so far just a little experience with T4, that's why I am asking.

I have such problem -- instead of having template which transforms itself into C# code (I would use T4 then) I have external file (template) which I would like to convert to C# code. Here (just an example!) I am building pretty limited (very limited) ORM. So my template looks like this:

Entry
*ID int
*Lang string
Text string

and this should be transformed to full class, which starts like this:

public class Entry
{
  public int ID { get; set; }
  public string Lang { get; set; }
  public string Text { get; set; }

  public object[] PrimaryKeys { get { return new object[] { ID, Lang }; } }

  public void ReadRecord(...
}

Question -- what is my next best step: should I my own converted or should I use T4 (or other similar tool).

The one advantage of my own tool I can think of is that IF I have/spend enough time, I could omit template file and create C# relying directly on database structure (in this case) instead of template file.

While answering please make this clear if you recommend your solution in both cases (input: text template vs. binary file, like db).

Remark: please, please, don't start with "why don't you use NHibernate/LS2/EF...". Thank you!

Upvotes: 0

Views: 997

Answers (1)

David Pope
David Pope

Reputation: 6587

I think T4 will work just fine for your needs. Check out the section "Design-time T4 text templates" in this MSDN link. It describes reading an XML configuration file to drive the code generation. You basically put the code that reads the input file into the first part of the .tt file, and then later reference what you read in as you lay out the classes.

Upvotes: 1

Related Questions