WCF Data Service的常规使用——客户端访问(3)
虽然WCF Data Service服务可以使用浏览器做查询访问,但是真正使用时大多数情况下还是需要使用程序代码。WCF Data Service基于WCF Rest构建,因此可以使用任何代码构建Http请求来访问服务,并且遵循rest与HTTP方法对应的约定。但对于.net3.5版本以后可以直接使用内置于.net framework中的OData SDK来访问WCF Data Service服务。OData SDK操作的语法与微软的Entity Framework非常相似,同样使用LINQ的语法(有个别方法不支持)。
本文所述与MSDN上的一篇文章类似,处于完整性,在这里简单的贴出代码,详细的描述请参考:
http://msdn.microsoft.com/zh-cn/library/dd756368.aspx
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DemoClient.DemoDataServiceReference; namespace DemoClient { class Program { private static DemoClient.DemoDataServiceReference.AdventureWorksEntities entities = new AdventureWorksEntities(new Uri("http://localhost:45669/WcfDataService.svc/")); public static void Main(string[] args) { Product p = QueryAProductById(800); Product[] ps = QueryProductsByColor("Black"); AddAProduct(); UpdateAProduct(); DeleteAProduct(); AddAProductWithCostHistory(); } ///由ID查询产品信息 private static Product QueryAProductById(int productId) { return entities.Product.Where<Product>(p => p.ProductID == productId).Single(); } //按颜色查询一批产品 private static Product[] QueryProductsByColor(string color) { return (from p in entities.Product where p.Color == color select p).ToArray(); } //选择一个商品及与之相关的CostHistory private static Product QueryAProductWithCostHistory(int productId) { return entities.Product.Expand("ProductCostHistory") .SingleOrDefault<Product>(p => p.ProductID == productId); } //添加新产品 调用 HTTP POST 方法 private static void AddAProduct() { Product p = Product.CreateProduct(0,"New Product","MY-001", true, true, 100, 75, 199.99m, 259.99m,7, DateTime.Today, Guid.NewGuid(), DateTime.Now); entities.AddToProduct(p); entities.SaveChanges(); } //修改现有产品 调用 HTTP MERGE 方法 private static void UpdateAProduct() { Product p = QueryAProductById(800); p.Name = "New Product Name"; entities.UpdateObject(p); entities.SaveChanges(); } //删除现有产品 调用 HTTP DELETE 方法 private static void DeleteAProduct() { Product p = QueryAProductById(800); entities.DeleteObject(p); entities.SaveChanges(); } //插入一组关联的对象 private static void AddAProductWithCostHistory() { Product p = QueryAProductById(800); ProductCostHistory ch = ProductCostHistory .CreateProductCostHistory(p.ProductID, DateTime.Today, 50m, DateTime.Now); entities.AddRelatedObject(p, "ProductCostHistory", ch); entities.UpdateObject(p); entities.SaveChanges(); } } }