DLINQ和XLINQ的具體查詢,更新等操作不是本文討論重點,本文重點解決如何獲取需要查詢的數據集。
DLINQ 如何鏈接到數據庫?
DLINQ可以訪問DataSet,這種情況我們在本文就不考慮了,
本文考慮的是直接用DLINQ訪問數據庫,我們如果用VS Orcas中的LINQ到SQL的新ORM設計器,VS替我們產生了一些代碼,這種情況也不是本文考慮的范圍。
本文我們要考慮的事情是:如何自己編碼去鏈接數據庫,這樣我們才能對DLINQ鏈接數據庫有更深入的了解。
下面是一個簡單的DLINQ代碼:獲得 pubs 數據庫 authors 表的所有作者的 au_id 信息。
using System;
using System.Linq;
using System.Data.Linq; // 這個命名空間在單獨的組件 System.Data.Linq.dll 中
public class DLinqTest
{
public static void DoSomeThing()
{
// 鏈接字符串
string connectionString = "Data Source=192.168.5.2;Initial Catalog=pubs;Persist Security Info=True;User ID=sa;PassWord=******";
// 我們就是通過使用 DataContext 來 DLINQ鏈接數據庫的。
DataContext db = new DataContext(connectionString);
Table<Authors> authors = db.GetTable<Authors>();
var users = from a in authors orderby a.au_id select a;
foreach (var a in users)
{
Console.WriteLine(a.au_id);
}
}
}
// 數據庫中的表結構影射的實體對象,注意其中的 Attribute.
[Table(Name = "authors")]
public class Authors
{
[Column(IsPRimaryKey = true)]
public string au_id { get; set; }
[Column]
public string au_lname { get; set; }
[Column]
public string au_fname { get; set; }
[Column]
public string phone { get; set; }
[Column]
public string city { get; set; }
[Column]
public string state { get; set; }
[Column]
public string zip { get; set; }
[Column]
public bool contract { get; set; }
}
DLINQ 鏈接到數據庫的步驟:
1、創建數據表跟實體對應的實體類(字段和元素可以不一一對應),并把這個類標上Table 特性,根數據表字段有關的元素標上Column特性;
2、使用 DataContext 和數據庫鏈接字符串建立跟數據庫的鏈接,然后使用 DataContext 的實例的 GetTable 方法獲得對應表影射的實體類。
XLINQ 訪問 xml 文件的方法
XLINQ 的例子我們就寫稍稍復雜點,通過獲得我(蟈蟈俊)博客的rss,然后把RSS中的鏈接和標題打印出來:
下面就是這個功能的演示代碼:
using System;
using System.Linq;
using System.Xml.Linq;
public class XLINQ
{
public static void DoSomeThing()
{
XElement feed = XElement.Load("http://blog.joycode.com/ghj/Rss.aspx");
if (feed.Element("channel") == null)
return;
var rss = from item in feed.Element("channel").Elements("item")
select new
{
title = item.Element("title").Value,
link = item.Element("link").Value
};
foreach (var item in rss)
{
Console.WriteLine(item.link);
Console.WriteLine(item.title);
Console.WriteLine("*****");
}
}
}
XLINQ 加載數據的核心就在于 XElement.Load
另外,上述代碼中使用了匿名類型,不知道大家還記不得我前幾篇博客設計到的這個知識點。
新聞熱點
疑難解答