Dapper Contrib Data Annotation


Data annotation adds some extra meaning to the classes and properties by adding attribute tags. It is used to configure the classes, which will highlight the most commonly needed configurations.

The Dapper.Contrib library provides some optional attributes which are very helpful.

Attribute Description
Key To make the corresponding column a primary key (PK) column in the database.
Table Create a table with a specified name in the Table attribute for a given domain class.
ExplicitKey Specify the property is a key that is NOT automatically generated by the database.
Write Specify if the property is writable or not.
Computed Specify the property should be excluded from update.

Key

The Key attribute specifies the property is a primary key column in the database.

class Author
{
    [Key]
    public int AuthId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Book> Books { get; set; }
}

Table

By default, the pluralized name of the class is used as a table name. You can use another table name by specifying the Table attribute.

[Table("tbl_Author")]
class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Book> Books { get; set; }
}

ExplicitKey

The ExplicitKey attribute represents that this property is a key that is not automatically generated by the database.

class Book
{
    [ExplicitKey]
    public int Id { get; set; }
    public string Title { get; set; }
    public string Category { get; set; }
    public int AuthorId { get; set; }
}

Write

The Write attribute specifies that the property is writable or not to the database.

class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [Write(false)]
    public List<Book> Books { get; set; }
}

Computed

You can use computed columns in the database and decorate your entity with the [Computed] attribute to prevent updating its value to the table.

class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [Write(false)]
    [Computed]
    public string FullName 
    { 
        get
        {
            return FirstName + " " + LastName;
        } 
    }

    [Write(false)]
    public List<Book> Books { get; set; }
}