Linq to SQL訪問數據庫描述
在向大家詳細介紹Linq之前,首先讓大家了解下使用Linq to SQL訪問數據庫,包括介紹建立一個C# Console Application測試我們的ORM。
使用Linq to SQL訪問數據庫
我們首先新建一個工程。為了簡單起見,我們就直接建立一個C# Console Application測試我們的ORM吧。將這個工程命名為LinqToSqlDemo.Test。當然,建好工程后,不要忘了添加對工程LinqToSqlDemo.Orm的引用,還要添加對“System.Data.Linq”命名空間的引用。
然后,我們打開Program.cs文件,將其中的內容替換為如下測試代碼。
- using System;
- using System.Collections.Generic;
- using System.Data.Linq;
- using System.Linq;
- using System.Text;
- using LinqToSqlDemo.Orm;
- namespace LinqToSqlDemo.Test
- {
- class Program
- {
- private static DataClassesDataContext
dataContext = new DataClassesDataContext();- private static void Output()
- {
- //輸出分類信息
- foreach (Category c in dataContext.Categories)
- {
- Console.WriteLine("分類" + c.ID + ":" + c.Name);
- }
- //輸出體育新聞下的公告信息
- Category categorySport = dataContext.Categories.Single(c => c.Name == "體育新聞");
- foreach (Bulletin b in categorySport.Bulletins)
- {
- Console.WriteLine("標題:" + b.Title);
- Console.WriteLine("內容:" + b.Content);
- Console.WriteLine("發布日期:" + b.Date);
- Console.WriteLine("所屬分類:" + b.Category1.Name);
- }
- }
- private static void TestInsert()
- {
- //生成分類實體類
- Category category1 = new Category()
- {
- Name = "國際要聞"
- };
- Category category2 = new Category()
- {
- Name = "體育新聞"
- };
- Category category3 = new Category()
- {
- Name = "財經快報"
- };
- //生成公告實體類
- Bulletin bulletin1 = new Bulletin()
- {
- Content = "曼聯晉級冠軍杯四強",
- Date = DateTime.Now,
- Title = "曼聯晉級冠軍杯四強"
- };
- Bulletin bulletin2 = new Bulletin()
- {
- Content = "18:00直播亞冠首爾VS山東,敬請期待!!!",
- Date = DateTime.Now,
- Title = "18:00直播亞冠首爾VS山東"
- };
- //將公告加入相應分類
- category2.Bulletins.Add(bulletin1);
- category2.Bulletins.Add(bulletin2);
- //加入數據庫
- dataContext.Categories.InsertOnSubmit(category1);
- dataContext.Categories.InsertOnSubmit(category2);
- dataContext.Categories.InsertOnSubmit(category3);
- dataContext.SubmitChanges();
- }
- private static void TestDelete()
- {
- dataContext.Categories.DeleteOnSubmit
(dataContext.Categories.Single(c => c.Name == "國際要聞"));- dataContext.SubmitChanges();
- }
- private static void TestUpdate()
- {
- Category categoryFinance = dataContext.
Categories.Single(c => c.Name == "財經快報");- categoryFinance.Name = "財經新聞";
- dataContext.SubmitChanges();
- }
- static void Main(string[] args)
- {
- Console.WriteLine("===Linq to SQL 測試===");
- Console.WriteLine();
- Console.WriteLine("===測試Insert===");
- Console.WriteLine();
- TestInsert();
- Output();
- Console.WriteLine("===測試Delete===");
- Console.WriteLine();
- TestDelete();
- Output();
- Console.WriteLine("===測試Update===");
- Console.WriteLine();
- TestUpdate();
- Output();
- Console.ReadLine();
- }
- }
- }
我們先來看看這段測試程序做了什么事。剛開始,數據庫是空的,我們首先插入三個分類,并在“體育新聞”下插入兩條公告,這是對Insert的測試。接著,我們刪除了“國際要聞”分類,這是對Delete的測試。然后,我們將“財經快報”改為“財經新聞”,這是對Update測試。另外,整個過程的輸出當然是對Select的測試。這樣,數據庫基本的操作都測試過了。從輸 出結果來看,我們的ORM組件運行很順利,程序輸出正確。以上介紹使用Linq to SQL訪問數據庫。
【編輯推薦】