I posted a while back about a way to embed in metadata about an entity’s tables and columns into the entity itself. This is useful if you disable the auto select and auto named parameters features of PetaPoco. However, I realized how bad what I did actually was. The approach I took, to embed that information into the entity, violated the Singular Responsibility Principal (SRP), which states that each object should have a singular responsibility, and doing this gave it two responsibilities. So instead, I decided to use an alternative solution.
For my needs, a repository pattern was helpful to centralize the location of all my queries. However, I didn’t want to worry about a grandiose repository scheme; I really needed something very simple, as the project this is for is very small. So I chose to embed the repository into the PetaPoco.Generator.include T4 template.
Below is my added repository, which contains those useful methods. Again, you may not need this, but if you want to get the most speed out of PetaPoco, it’s something to consider:
public partial class Repository
{
protected string[] GetColumns()
{
return new string[]
{
<#
for(int i = 0, len = tbl.Columns.Count; i
“”
};
}
protected Sql GetBaseSelectSql()
{
return new Sql()
.Select(GetColumns())
.From(“”);
}
protected string GetTableName()
{
return “”;
}
public Get(int id)
{
var ctx = new ();
return ctx.FirstOrDefault<>(this.GetBaseSelectSql().Where(“=@0”, id));
}
public void Create( obj)
{
if (obj == null)
throw new ArgumentNullException(“obj”);
var ctx = new ();
ctx.Insert(“”, “”, obj);
}
public void Delete( obj)
{
if (obj == null)
throw new ArgumentNullException(“obj”);
var ctx = new ();
ctx.Delete(“”, “”, obj);
}
public void DeleteByKey(int id)
{
var ctx = new ();
ctx.Execute(“delete from where = @0”, id);
}
public void Update( obj)
{
if (obj == null)
throw new ArgumentNullException(“obj”);
var ctx = new ();
ctx.Update(“”, “”, obj);
}
}
RepoName is the name to the core PetaPoco repository for working with data objects. Notice how in the modification methods (create, update, delete), for performance improvements, it provides the table/PK name, which the T4 template will inject and code generate. Additionally, some queries are generated too (Get and DeleteByKey), which we could take to a further degree. And lastly, at the top, are our helpful methods for referring to fields.
I placed this at the top of the generate poco’s IF statement, but before the entity definition as in the following. At the time of writing, this is at line 134.
<#
//POCO definition
[TableName(“”)]
[PrimaryKey(“”)]
[PrimaryKey(“”, sequenceName=””)]
[PrimaryKey(“”, autoIncrement=false)]
[ExplicitColumns]
public partial class : .Record<>
{