除了 SQL 敘述之外,透過 DataSet 直接萃取資料,還必須進一步自行處理資料類別的細節,我們可以利用 LINQ to SQL 來達到需要的效果,同「LINQ 與資料存取 (4) - 透過 LINQ to SQL 進行資料表查詢」討論的內容,這一個小特來看看相關的作法,參考其中對 LINQ to SQL的設定,現在另外建立一個新的網頁,配置需要的程式碼以從資料庫萃取資料於網頁呈現。
需要的 LINQ to SQL 對應類別如下:
接下來以指定的連線字串,建立 Context 物件,取出 Products 資料表的內容,最後將資料繫結至 GridView 控制項,展示資料內容。
變數 table 封裝了資料表內容資料,緊接著透過不同的 LINQ 敘述,取出需要的局部資料,繫結至另外兩個 GridView 控制項。
這個範例的邏輯以及所要達到的結果,與「LINQ 與資料存取:ASP.NET篇(3)- Why LINQ」這一篇所討論的完全相同,因此讀者只需瞭解其中一開始建立 Context 物件的關鍵差異即可。
》LINQ 與資料存取系列
需要的 LINQ to SQL 對應類別如下:
[Table(Name = "Products")]
public class Product
{
public Product()
{
}
public Product(int pid, string name, int price, int cid)
{
this.productID = pid;
this.productName = name;
this.unitPrice = price;
this.categoryID = cid;
}
[Column]
public int productID { get; set; }
[Column]
public string productName { get; set; }
[Column]
public int unitPrice { get; set; }
[Column]
public int categoryID { get; set; }
}
接下來以指定的連線字串,建立 Context 物件,取出 Products 資料表的內容,最後將資料繫結至 GridView 控制項,展示資料內容。
SqlConnection conn = new SqlConnection(
@"Server=Tim-PC;DataBase = KTMS ;Trusted_Connection=True ; ");
DataContext dc = new DataContext(conn);
Table<Product> table = dc.GetTable<Product>();
gridView.DataSource = table;
gridView.DataBind();
變數 table 封裝了資料表內容資料,緊接著透過不同的 LINQ 敘述,取出需要的局部資料,繫結至另外兩個 GridView 控制項。
var rows_books =
from row in table
where row.categoryID.ToString() == "101068"
select row;
gridView_books.DataSource = rows_books;
gridView_books.DataBind();
var rows_html5 =
from row in table
where row.productName.ToString().Contains("HTML5")
select row;
gridView_html5.DataSource = rows_html5;
gridView_html5.DataBind();
這個範例的邏輯以及所要達到的結果,與「LINQ 與資料存取:ASP.NET篇(3)- Why LINQ」這一篇所討論的完全相同,因此讀者只需瞭解其中一開始建立 Context 物件的關鍵差異即可。
》LINQ 與資料存取系列
沒有留言:
張貼留言