ADO.NET Data Services (代號 Astoria) 旨在為資料導向服務提供基於 REST 的統一框架,讓企業內部網或網際網路的所有 Web 用戶端能以統一介面存取資料。框架包含伺服器端庫 (安全公開資料) 與多種用戶端庫 (.NET、Silverlight、AJAX),支援豐富互動網頁應用 (RIA) 與資料混合應用。

實體 = 含鍵值的結構化記錄 (如 Customer、Order)。實體集 = 實體集合 (Customers)。關聯 = 實體類型間連結 (Employee WorksFor Department)。EDM 完美對應 Web 資源與連結概念。
優勢:單一資料模型服務多種應用 (報表、入口網站、工作流),並與 ADO.NET Entity Framework 共享模型定義。
DataService<NorthwindEntities>public class NorthwindService : DataService<NorthwindEntities> {
public static void InitializeService(IDataServiceConfiguration config) {
config.SetEntitySetAccessRule("*", EntitySetRights.All); // 開放所有
}
}
瀏覽器訪問 /NorthwindService.svc 即可看到 Atom 格式的實體集清單。
實作 IQueryable<T> 屬性公開記憶體內集合:
public class User { public int ID {get;set;} public string Name {get;set;}
public IList<Contact> Contacts {get;set;} }
public class Contact { public int ID {get;set;} public string Name {get;set;}
public string Email {get;set;} }
public class MyDataService {
static User[] _users; static Contact[] _contacts;
static MyDataService() { /* 初始化測試資料 */ }
public IQueryable<User> Users => _users.AsQueryable();
public IQueryable<Contact> Contacts => _contacts.AsQueryable();
}
// 服務掛載
public class ContactsService : DataService<MyDataService> {
public static void InitializeService(IDataServiceConfiguration config) {
config.SetEntitySetAccessRule("*", EntitySetRights.All);
}
}
生產環境中 IQueryable 提供者會將運算式樹轉換為資料來源原生查詢 (如 LINQ to Entities → SQL)。
https://host/vdir/service.svc/EntitySet[(Key)][/NavigationProperty[(Key)]...]
範例 (Northwind):
/Customers — 所有客戶/Customers('ALFKI') — 單一客戶/Customers('ALFKI')/Orders — 該客戶訂單 (導覽屬性)查詢字串參數:
$filter=City eq 'London' — 篩選$expand=Orders — 主動載入關聯$orderby=City asc — 排序$skip=10&$top=20 — 分頁SetEntitySetAccessRuleconfig.SetEntitySetAccessRule("Customers", EntitySetRights.All);
config.SetEntitySetAccessRule("Orders", EntitySetRights.ReadSingle); // 單筆讀取
config.SetEntitySetAccessRule("Products", EntitySetRights.WriteInsert | EntitySetRights.WriteUpdate); // 不可刪除
[QueryInterceptor("Orders")]
public Expression<Func<Orders,bool>> OnQueryOrders()
=> o => o.Customer.ContactName == HttpContext.Current.User.Identity.Name;
DataServiceContext (執行階段上下文、身分解析、開放式並行)、DataServiceQuery<T> (URI 查詢表示)datasvcutil.exe 命令列工具from c in ctx.Customers where c.City=="London" orderby c.CompanyName select c (自動轉譯為 URI)context.LoadProperty(entity, "NavigationProperty") 延遲載入,或 URI $expand 主動載入| 操作 | HTTP 動詞 | 用戶端 API |
|---|---|---|
| Create | POST | context.AddObject("EntitySet", entity); context.SetLink(...); context.SaveChanges(); |
| Update | PUT | context.AttachTo(...); context.UpdateObject(entity); context.SaveChanges(); |
| Delete | DELETE | context.AttachTo(...); context.DeleteObject(entity); context.SaveChanges(); |
SaveChanges() 批次提交所有掛起變更。支援 SaveChangesOptions.Batch 單一 HTTP 請求原子提交,或 ExecuteBatch 合併多查詢。
ADO.NET Data Services 提供標準化、可擴充的資料服務平台:REST/AtomPub 介面確保跨平台互通,EDM 模型統一語義,豐富用戶端庫降低開發門檻,安全機制滿足企業級需求。適用於 RIA 資料層、公開 API、資料混合應用等多種場景。