Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
From the author of

Mapping Entity Classes to Tables

A class is called an entity when it maps to a table in a database. To map a class to a database table, decorate the class with the TableAttribute naming the underlying table and decorate each property with the ColumnAttribute naming the underlying column.

Somewhere I read that the AdventureWorks database that ships with SQL Server 2005 is intended to replace the ubiquitous Northwind database. (Old Northwind is getting stale, I guess.)

The example in Listing 1 maps the CreditCard table to a CreditCard class. The sample uses .NET 3.5, Visual Studio 2008, and SQL Server 2005 and the AdventureWorks database.

Listing 1 An entity class mapped to the CreditCard table of the AdventureWorks database in the Sales schema.

  [Table(Name="Sales.CreditCard")] // maps class to table
  public class CreditCard
    [Column(IsPrimaryKey=true)]           //maps property to column
    public int CreditCardID{ get; set; }  // uses automatic property
    public string CardType{ get; set; }
    public string CardNumber{ get; set; }
    public byte ExpMonth{ get; set; }     // tinyint = byte
    //public Int16 ExpYear{ get; set; }   // smallint = Int16
    public int ExpYear { get; set; }
    public DateTime ModifiedDate{ get; set; }

The TableAttribute uses the Name named argument to indicate that the class CreditCard is mapped to Sales.CreditCard. The ColumnAttribute specifies the associated underlying column. If you don't specify the IsPrimaryKey named argument, you can't perform updates. Also, you don't need to express the DbType named argument unless you don't match the C# type to the correct DbType. For example, to define ExpYear as an integer, you need to use the DbType argument and indicate that the column type is a smallint. As an alternate approach, you can use the default ColumnAttribute and indicate that the property type is an Int16. Using a property type that's equivalent to the field type or expressing the DbType argument for the ColumnAttribute is a suitable way to map a property to a column.

  • + Share This
  • 🔖 Save To Your Account