I am trying to generate the below code via T4.
using System;
using MyDAL;
namspace Test
{
// Select...
public partial class MyCustomer
{
public int id { get ;set;}
public string name { get ;set;}
public string surname { get ;set;}
public MyCustomer()
{
}
public List<Customer> GetById(int id)
{
// do something...
}
}
// Delete,Update,Save
public partial class MyCustomer
{
public bool Save(new MyCustomer)
{
// do something...
}
public bool delete(int id)
{
// do something...
}
public bool Update(int id)
{
// do something...
}
}
}
The T4 template I have so far:
<#@ template language="C#"#>
<#@ assembly name="Microsoft.SqlServer.Management.Sdk.Sfc" #>
<#@ assembly name="Microsoft.SqlServer.ConnectionInfo" #>
<#@ assembly name="Microsoft.SqlServer.Smo" #>
<#@ import namespace="Microsoft.SqlServer.Management.Smo" #>
namespace DbClasses
{
<#
Server srv = new Server();
Database db = new Database(srv,"NarDb");
db.Refresh();
foreach (Table tablo in db.Tables)
{
WriteLine("public class " +tablo.Name+"{");
foreach (Column column in tablo.Columns)
{
if(column.DataType.Name=="nvarchar")
WriteLine("public "+"string " +""+column.Name+";");
else
WriteLine("public "+"int " +""+column.Name+";");
}
WriteLine("}");
}
#>
}
I’m not exactly sure what is the problem you are facing: but there is nothing wrong with your T4 code. The signature of the Save method in the second class has new and that’s an error:
should be
Also, GetById should return one element not a list.
I tried out the code you wrote without connecting to a database by writing dummy classes for Table, Column, etc and there is nothing wrong with the T4 code you wrote, except that, as per your requirements, the code your wrote doesn’t generate partial classes, not does it create properties. It just creates a single non-partial class for each table with public fields (not properties). If you want to generate partial classes and properties (and methods) you’re in the right direction (I added tabs and newlines to make it look pretty in the generated file, you can just press Ctrl+K, Ctrl+D there to reformat it though: