首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

精進不休 .NET 4.0 (6):ADO.NET Data Services 1.5 新特性

     編輯:關於.NET

Data Services 1.5 新增功能

  • 伺服端 $count(RowCount):只回傳實體集合筆數。
  • 伺服端分頁:SetEntitySetPageSize 限制每頁筆數,配合 $skip/$inlinecount。
  • 伺服端 $select:投影指定欄位,減少傳輸量。
  • 二進位大物件 (BLOB) 串流傳輸:IDataServiceStreamProvider。
  • 自訂資料服務:不需 Entity Framework,直接以 IQueryable 暴露記憶體集合。

服務端共同設定

public class MyDataService : DataService<AdventureWorksEntities>
{
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        config.SetEntitySetAccessRule("Products", EntitySetRights.All);
        config.SetEntitySetPageSize("Products", 5); // 分頁每頁 5 筆
    }
}

1. $count / $inlinecount Demo

// 用戶端
var count = context.Products.Count(); // 對應 $count
// URI: /Products/$count

// 分頁含總筆數
var products = context.Products.Skip(10); // $skip=10
// URI: /Products?$skip=10&$inlinecount=allpages

2. 伺服端分頁 Demo

服務端 SetEntitySetPageSize("Products", 5),用戶端用 Skip() 翻頁,回傳內含 __count 欄位(若加 $inlinecount=allpages)。

3. $select 投影 Demo

var products = context.Products.Select(p => new { p.ProductID, p.Name });
// URI: /Products?$select=ProductID,Name

4. BLOB 串流傳輸

  1. EDMX 概念模型實體加上 m:HasStream="true"。
  2. 服務實作 IServiceProvider,GetService 回傳自訂 IDataServiceStreamProvider。
  3. Provider 實作 GetReadStream 回傳 MemoryStream,GetStreamContentType 回傳 MIME。
public class ProductPhotoStreamProvider : IDataServiceStreamProvider
{
    public Stream GetReadStream(object entity, ...)
    {
        var product = (Product)entity;
        return new MemoryStream(product.ThumbNailPhoto);
    }
    public string GetStreamContentType(object entity, ...) => "image/jpeg";
    public int StreamBufferSize => 64;
    // 其他成員拋 NotImplementedException
}

前端直接用 <img src="/Products(714)/$value" /> 顯示圖片。

5. 自訂資料服務

繼承 DataService<CustomContext>,CustomContext 暴露 IQueryable<T> 屬性。實體類別加 [DataServiceKey] 指定主鍵,[EntityPropertyMapping] 映射 ATOM 欄位。

[DataServiceKey("OrderId")]
[EntityPropertyMapping("Customer", SyndicationItemProperty.AuthorName, SyndicationTextContentKind.Plaintext, true)]
public class Order { public int OrderId { get; set; } public string Customer { get; set; } public List<Product> Items { get; set; } }

URI 查詢語法總表

https://[Url]/[ServiceName]/[EntityName]/[NavigationOptions]?[QueryOptions]

  • $count、$inlinecount=none/allpages
  • $skip=n、$top=n
  • $select=col1,col2
  • $filter=...、$orderby=...、$expand=...

總結

Data Services 1.5 大幅強化了 OData 協定支援,特別是分頁、投影、計數與串流,讓 RESTful 資料服務更實用、效能更佳。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved