Database Reference
In-Depth Information
Table<Contact> contacts = db.GetTable<Contact>();
To be consistent the [Column] attribute marks a field as one that will hold data from a table. You can
declare fields in an entity class that don't map to table columns, and LINQ will just ignore them, but
those decorated with the [Column] attribute must be of types compatible with the table columns they
map to. (Note that since SQL Server table and column names aren't case sensitive, the default names do
not have to be identical in case to the names used in the database.)
You create a data context .
// Create data context
DataContext db = new DataContext(connString);
A data context does what an ADO.NET connection does, but it also does things that a data provider
handles. It not only manages the connection to a data source but also translates LINQ requests
(expressed in SQO) into SQL, passes the SQL to the database server, and creates objects from the result
set.
You create a typed table .
// Create typed table
Table<Contact> contacts = db.GetTable<Contact>();
A typed table is a collection (of type System.Data.Linq.Table<T> ) whose elements are of a specific
type. The GetTable method of the DataContext class tells the data context to access the results and
indicates where to put them. Here, you get all the rows (but only three columns) from the
Person.Contact table, and the data context creates an object for each row in the contacts typed table.
You declare a C# 2012 implicitly typed local variable, contactDetails , of type var .
// Query database
var contactDetails =
An implicitly typed local variable is just what its name implies. When C# sees the var type, it infers
the type of the local variable based on the type of the expression in the initializer to the right of the =
sign.
You initialize the local variable with a query expression .
from c in contacts
where c.Title == "Mr."
orderby c.FirstName
select c;
A query expression is composed of a from clause and a query body. You use the WHERE condition in
the query body here. The from clause declares an iteration variable, c , to be used to iterate over the result
of the expression, contacts (that is, over the typed table you earlier created and loaded). In each
iteration, it will select the rows that meet the WHERE clause (here, the title must be “Mr.”).
Finally, you loop through the custs collection and display each customer.
// Display contact details
foreach (var c in contactDetails)
{
txtLinqtoSql.AppendText(c.Title);
txtLinqtoSql.AppendText("\t");
txtLinqtoSql.AppendText(c.FirstName);
txtLinqtoSql.AppendText("\t");
txtLinqtoSql.AppendText(c.LastName);
txtLinqtoSql.AppendText("\n");
 
Search WWH ::




Custom Search