- Introduction
- LINQ to SQL in a Nutshell
- Mapping Entity Classes to Tables
- Defining a Custom DataContext
- Querying the CreditCard Table with LINQ
- Summary
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 [Column()] public string CardType{ get; set; } [Column()] public string CardNumber{ get; set; } [Column()] public byte ExpMonth{ get; set; } // tinyint = byte //[Column()] //public Int16 ExpYear{ get; set; } // smallint = Int16 [Column(DbType="smallint")] public int ExpYear { get; set; } [Column()] 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.