Книга: C# 2008 Programmer

Querying

Querying

With the database modeled using the LINQ to SQL designer, it's time to write some code to query the database. First, create an instance of the DataClasses1DataContext class:

DataClasses1DataContext database = new DataClasses1DataContext();

To retrieve all the authors living in CA, use the following code:

var authors = from a in database.authors
 where (a.state == "CA")
 select new {
  Name = a.au_fname + " " + a.au_lname
 };
foreach (var a in authors)
 Console.WriteLine(a.Name);

To retrieve all the titles in the titles table and at the same time print out the publisher name of each title, you first retrieve all the titles from the titles table:

var titles = from t in database.titles
 select t;

And then you retrieve each title's associated publisher:

foreach (var t in titles) {
 Console.Write("{0} ", t.title1);
 var publisher =
  from p in database.publishers
  where p.pub_id == t.pub_id
  select p;
 if (publisher.Count() < 0)
  Console.WriteLine("({0})", publisher.First().pub_name);
}

The output looks something like this:

Cooking with Computers: Surreptitious Balance Sheets (Algodata Infosystems)
You Can Combat Computer Stress! (New Moon Books)
How to Motivate Your Employees Straight Talk About Computers (Algodata Infosystems)
Silicon Valley Gastronomic Treats (Binnet & Hardley)
The Gourmet Microwave (Binnet & Hardley)
The Psychology of Computer Cooking (Binnet & Hardley)
But Is It User Friendly? (Algodata Infosystems)
Secrets of Silicon Valley (Algodata Infosystems)
Net Etiquette (Algodata Infosystems)
Computer Phobic AND Non-Phobic Individuals: Behavior Variations (Binnet & Hardley)
Is Anger the Enemy? (New Moon Books)
Life Without Fear (New Moon Books)
Prolonged Data Deprivation: Four Case Studies (New Moon Books)
Emotional Security: A New Algorithm (New Moon Books)
Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean (Binnet & Hardley)
Fifty Years in Buckingham Palace Kitchens (Binnet & Hardley)
Sushi, Anyone? (Binnet & Hardley)

Оглавление книги


Генерация: 0.819. Запросов К БД/Cache: 2 / 0
поделиться
Вверх Вниз