LINQ to SQL

Throughout this book, we rely on LINQ to SQL to demonstrate interpreted queries. This section examines the key features of this technology.

LINQ to SQL Entity Classes

LINQ to SQL allows you to use any class to represent data, as long as you decorate it with appropriate attributes. Here’s a simple example:

[Table]
	public class Customer
	{
	  [Column(IsPrimaryKey=true)]
	  public int ID;
	  [Column]
	  public string Name;
	}

The [Table] attribute, in the System.Data.Linq.Mapping namespace, tells LINQ to SQL that an object of this type represents a row in a database table. By default, it assumes the table name matches the class name; if this is not the case, you can specify the table name as follows:

	[Table (Name="Customers")]

A class decorated with the [Table] attribute is called an entity in LINQ to SQL. To be useful, its structure must closely—or exactly—match that of a database table, making it a low-level construct.

The [Column] attribute flags a field or property that maps to a column in a table. If the column name differs from the field or property name, you can specify the column name as follows:

	[Column (Name="FullName")]
	public string Name;

The IsPrimaryKey property in the [Column] attribute indicates that the column partakes in the table’s primary key. It is required for maintaining object identity, as well as for allowing updates to be written back to the database.

Instead of defining public fields, you can define public properties in conjunction with private fields. This allows ...

Get LINQ Pocket Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.