RKh RKh - 2 months ago 29
C# Question

How to modify PetaPoco class to work with Composite key comprising of non-numeric columns?

I have a table with following columns:

ContractorId ......... INT ............. IDENTITY

ContractorName ........ Varchar(50) ....... P.K

ContractorGrade ....... Varchar(3) ....... P.K


The class generated by PetaPoco T4 template looks like this:

[TableName("contractor_master")]
[PrimaryKey("contractorname", autoIncrement=false)]
[ExplicitColumns]
public partial class contractor_master : TubewellRepo.Record<contractor_master>
{
[Column]
public int contractorid
{
get
{
return _contractorid;
}
set
{
_contractorid = value;
MarkColumnModified("contractorid");
}
}
int _contractorid;

[Column]
public string contractorname
{
get
{
return _contractorname;
}
set
{
_contractorname = value;
MarkColumnModified("contractorname");
}
}
string _contractorname;

[Column]
public string contractorgrade
{
get
{
return _contractorgrade;
}
set
{
_contractorgrade = value;
MarkColumnModified("contractorgrade");
}
}
string _contractorgrade;
}


The code to INSERT a new record is as below:

// Insert a record
var Contractor=new contractor_master();
Contractor.contractorname = "Super Borewells";
Contractor.contractorgrade = "A";

db.Insert(Contractor);


In the second line of the Class Code, I want to know how to mention a Composite Key, which is (ContractorName + ContractorGrade).

Secondly, it is not inserting a record because it expects an Id column. Even though ContractorId is IDENTITY, it is not a primary key.

It is not INSERTING a new record and gives error because it is inserting 0 in the IDENTITY column.

Answer

My branch here: https://github.com/schotime/petapoco supports composite primary key by specifying the PrimaryKey attribute like:

[PrimaryKey("ContractorName,ContractorGrade")]

I'm not sure how it will work if you want the identity column there as well.

Comments