Visual Studio 2008開發新特性系列課程(4):VS2008新特性之LINQ實戰

1.linq 框架
---------------------------------------------------------
C# VB
---------------------------------------------------------
.Net Language INtegrated Query(LINQ)
---------------------------------------------------------
Linq enabled data sources
1.linq to objects
2.Linq enabled ADO.NET
----linq to DataSet
----linq to SQL
----linq to Entities
3.linq to XML
---------------------------------------------------------
Data
Objects,Relations,XML
---------------------------------------------------------

 

2.LINQ for SQL
? 把.NET 類和SQL 數據通過關係進行映射(對象<--->關係的相互映射)
? 把LINQ 查詢轉化爲SQL 語言進行執行
? 支持對插入,更新,刪除操作進行跟蹤.
? 支持實體級別的驗證規則
? 構建於ADO.NET之上並且集成連接池和事ADO.務處理(ADO.NET之上)

舉例1:(查詢實例)
  NorthWindDataContext dc = new NorthWindDataContext();

            var query = from P in dc.Products
                        where P.CategoryID.Value>6
                        select P;
            this.GridView1.DataSource = query;
            this.GridView1.DataBind();

舉例2:(修改單個記錄實例)
NorthWindDataContext dc = new NorthWindDataContext();
            Product product = dc.Products.Single(p => p.ProductName == "Tofu");
    
            product.UnitPrice = 1111111111;
            product.UnitsInStock = 55;
            dc.SubmitChanges();


3.數據表映射
? 映射數據表和實體類之間的關係
? 使用數據庫中典型的主/外鍵進行表示
? 支持靈活的關係查詢並且不用寫任務的SQL
? 代碼就可以執行處理過程

舉例3:
-----產品類型 Categories<1>-----> <n>產品Products <n>
-----產品Products <n> <----<1>提供商 Suppliers

Table Suplier
-------------------------------------------------------
SuplierID
CompanyName
.....

Table Category
-------------------------------------------------------
CategoryID
CanegoryName
....

Table Product
-------------------------------------------------------
ProductID
ProductName
....
SuplierID
CategoryID

模型中的代碼關聯如下:
public partial class Product {
 public int ProductID;
 public string ProductName;
 public Nullable<int> SupplierID;
 public Nullable<int> CategoryID;

 public Supplier Supplier; //兩者組合以來,一對一
 public Category Category;  //兩者組合以來,一對一
}
public partial class Supplier {
 public int SupplierID;
 public string CompanyName;

 public EntitySet<Product> Products; //一對多
}
 public partial class Category {
 public int CategoryID;

 public EntitySet<Product> Products; //一對多
}
我們可以這樣理解:在對Product進行數據訪問的時候,可以直接訪問Supplier和Category的的單個對象;在對Supplier訪問時,可以訪問對於的一組Products對象;在對Category訪問時,可以訪問對於的一組Products對象;

舉例查詢1:(在Supplier裏面直接訪問Product)
            NorthWindDataContext db = new NorthWindDataContext();

            GridView1.DataSource = from s in db.Suppliers
                                   select new
                                   {
                                       Name = s.CompanyName,
                                       Country = s.Country,
                                       Products = from p in s.Products //在Supplier裏面直接訪問Products
                                                  select new
                                                  {
                                                      ProductName = p.ProductName
                                                  }
                                   };

            GridView1.DataBind();
        }

舉例2:(在Supplier裏面訪問Product)
NorthwindDataContext db = new NorthwindDataContext();
var suppliers = from s in db.Suppliers
  where s.Products.Count > 2
  select s;

foreach (Supplier supplier in suppliers) {
 Response.Write("<h3>" + supplier.CompanyName + "</h3>");
 foreach (Product product in supplier.Products) {
  Response.Write("-- ");
  Response.Write(product.ProductName);
  Response.Write("<br/>");
 }
}

舉例3:(使用一些函數)
NorthwindDataContext db = new NorthwindDataContext();
SupplierList.DataSource = from s in db.Suppliers
     where s.Products.Count > 2
     select s;
SupplierList.DataBind();

NorthwindDataContext db = new NorthwindDataContext();
GridView1.DataSource = (from s in db.Suppliers
   where s.Products.Count > 4
   select s).Including(s => s.Products)
GridView1.DataBind();

 

4.聯合查詢
舉例1:兩個表的join操作。

NorthWindDataContext db = new NorthWindDataContext();
var custTotalOrders = from c in db.Customers
                      join o in db.Orders
                       on c.CustomerID equals o.CustomerID into custOrders   //存放早custOrders的臨時結果集中
                       from o in custOrders //從這個結果集中繼續查詢
                       select new
                       {
                          Customer = c.CompanyName,
                          OrderDate = o.OrderDate,
                           OrderTotal = o.Order_Details.Sum(d => d.UnitPrice * d.Quantity)
                        };
GridView1.DataSource = custTotalOrders;
GridView1.DataBind();

舉例2:(直接查詢)
var innerJoinQuery =
    from category in categories
    join prod in products on category.ID equals prod.CategoryID
    select new { ProductName = prod.Name, Category = category.Name };

 

5.數據分頁
相對於以前的TSQL語句而言,不是一次把所有的數據都取出來,而是根據需要從數據庫中讀取數據。
int startRow = Convert.ToInt32(Request.QueryString["startRow"]);
NorthwindDataContext db = new NorthwindDataContext();
var results = from c in db.Customers join o in db.Orders
       on c.CustomerID equals o.CustomerID into custOrders
       from o in custOrders
       select new {
          Customer = c.CompanyName,
         OrderDate = o.OrderDate,
        OrderTotal = o.OrderDetails.Sum(d=>d.UnitPrice)
       };

GridView1.DataSource = results.Skip(startRow).Take(10);//分頁
GridView1.DataBind();


5.更新一個特定的產品
NorthwindDataContext db = new NorthwindDataContext();
Product product = db.Products.Single(p => p.ProductName== "Chai");
product.UnitsInStock = 11;
product.ReorderLevel = 10;
product.UnitsOnOrder = 2;
db.SubmitChanges();

6.插入記錄
Order ord = new Order
{
    OrderID = 12000,
    ShipCity = "Seattle",
    OrderDate = DateTime.Now
    // …
};

// Add the new object to the Orders collection.
db.Orders.InsertOnSubmit(ord);

// Submit the change to the database.
try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e);
    // Make some adjustments.
    // ...
    // Try again.
    db.SubmitChanges();
}

 

7.刪除記錄
var deleteOrderDetails =
    from details in db.OrderDetails
    where details.OrderID == 11000
    select details;

foreach (var detail in deleteOrderDetails)
{
    db.OrderDetails.DeleteOnSubmit(detail);
}

try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e);
    // Provide for exceptions.
}

 

8.其它的LINQ for SQL 功能
? 能夠執行實體/屬性驗證
? 可以使用存儲過程和視圖
? 可以清晰地定義和參與內部的TransactionScope()操作(簡單分佈式事務的寫法,可以指定事務是否包含在上一層事務中,通過DataContex制定)
? 實體類型的保存可以使用同一個DataContext進行多種數據查詢

 

9.LINQ to XML
以前的操作方式:流的方式、結點的方式

? XML 文檔的更好的操作
? 支持language integrated queries
? 更方便,更快速更智能更簡單的XML API

NorthwindDataContext db = new NorthwindDataContext();
 XElement rssRoot = new XElement("rss",
 new XAttribute("version", "2.0"),
 new XElement("channel"
  new XElement("title", "My RSS Feed"),
  new XElement("link", "http://weblogs.asp.net"),
  new XElement("description", "Northwind Products Feed"),
 from product in db.Products
 orderby product.ProductName descending
 select new XElement("item",
  new XElement("title", product.ProductName),
  new XElement("link", “p.aspx?id="+product.ProductID),
  new XElement("description", "Supplier: " +
  product.Supplier.CompanyName)
 )
 )
);
Response.Write(rssRoot.ToString());

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章