Knight Data Access Layer
Mapping By Attributes
Basic Tasks C# > Mapping > Mapping By Attributes

The Knight Data Access Layer uses POCO (Plain Old C# Objects).  There is no requirement to inherit from any base class or interface or make methods virtual.  Classes are mapped to tables, and class properties are mapped to fields in the database.  This mapping is automatic.  When mapping, Knight .NET Data Access Layer will look for a table with the same name as the class name.  If it does not find a table with the same name, it makes the name plural and then tries to match that.  Properties and database columns are matched exactly by the name.  Primary keys can by Id or TableNameId.  Attributes can override the default mapping behavior.

No Attributes Syntax

No attributes are required on this Customer class.  It is assumed there is either a Customer table or a Customers table with columns that match exactly to the property names.

public class Customer

{

    public long CustomerId { get; set; }

    public string Name { get; set; }

    public DateTime DateCreated { get; set; }

    public IList<string> FavoriteFoods { get; set; }

}

 

Attribute Syntax


Here is an example of a class that is dramatically different than the table it is mapped to.  Attributes can be used to override the default mapping behavior.

 

[TableMapping("Customers")]

public class Customer3

{

   [ColumnMapping("CustomerID",System.Data.DbType.Int32),PrimaryKey(PrimaryKeyType.Identity)]

   public int ID { get; set; }

   [ColumnMapping("FirstName",System.Data.DbType.String,50),Nullable,Caption("First Name"),DefaultValue("Greg")]

   public string FName { get; set; }

   [ColumnMapping("LastName",System.Data.DbType.String,50),Nullable,Caption("Last Name")]

   public string LName { get; set; }

}