Dapper Tutorial Dapper Contrib - Data Annotation - Key

Description

The Data Annotation Key Attribute is used to specify the primary key of a table. It is applied to a property of a class that maps to a primary key column in a database table. It specifies the property as a key that is automatically generated by the database (Identity Column).

  • The Key attribute can be applied to a property in an entity class to make it a key property and the corresponding column in the database table will be configured as a primary key.
  • When the Key attribute is applied to a property, the property becomes a part of the entity's key and cannot be changed or assigned a new value.
  • An error will be generated if we try to update the key property.

In the following example, the InvoiceID is decorated with a Key attribute to specify the primary key of a table.

[Table("Invoice")]
public class InvoiceContrib
{
	[Key]
	public int InvoiceID { get; set; }

	public string Code { get; set; }
	public InvoiceKind Kind { get; set; }

	[Write(false)]
	[Computed]
	public string FakeProperty { get; set; }
}

using (var connection = My.ConnectionFactory())
{
	connection.Open();

	var identity = connection.Insert(new InvoiceContrib {Kind = InvoiceKind.WebInvoice, Code = "Insert_Single_1"});
}