WCF Data Services客户端访问
上一篇http://www.cnblogs.com/2018/archive/2010/10/17/1853384.html
讲述了查询的相关语法和例子,如果在程序中如何使用这些发布的服务呢?下面对在代码中访问这些服务的方法进行一下汇总
客户端访问
查询 |
这些查询中可以结合上文的查询语法等使用 Ø 浏览器地址:输入地址,GET请求直接进行 Ø JavaScipt库:如ExtJS、DOJO、MS AJAX等支持JSON处理的JS库 Ø Service Reference引用 常用的形式,IDE直接添加引用,使用代理对象和上下文处理 //Generic泛型 { DataServiceContext ctx = new DataServiceContext(u); var q = ctx.Execute<Order>(new Uri("/Orders(10402)", UriKind.Relative)); foreach (var t in q) { Console.WriteLine(t.OrderDate); } } //Client Proxy代理 { NorthwindEntities ctx = new NorthwindEntities(u); var q = from c in ctx.Suppliers select c; foreach (var t in q) { Console.WriteLine(t.City); } Ø HTTP协议支持处理 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url + "/Orders(10402)"); req.Method = "GET"; req.Accept = "application/json"; using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) { using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { Console.WriteLine(sr.ReadToEnd()); } } req = (HttpWebRequest)WebRequest.Create(url + "/Orders(10402)"); req.Method = "GET"; req.Accept = "application/atom+xml"; using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) { using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { XmlDocument xml = new XmlDocument(); xml.Load(sr); Console.WriteLine(xml.InnerXml); } } |
增删改 |
Ø HTTP形式 参考MSDN的规定传递参数和请求形式即可,处理有些麻烦 Ø Service Reference引用 比较常用的形式,具体参考“修改数据”一节 需要处理并发冲突: DataServiceRequestException · Entity Framework provider - In the data model, the ConcurrencyMode attribute of a property that is part of the concurrency token for an entity type is set to Fixed. · Reflection provider - The ETagAttribute is applied to the data class that is an entity type. This attribute declares the concurrency token based on the supplied property names. |
修改数据
Insert |
HTTP POST Content-Type:需正确设置 |
Update |
HTTP Put/Merger |
Delete |
HTTP Delete |
例子
需要修改数据对象,注意服务端需要设置正确的属性,如:
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
客户端通过代理访问:
//Client Proxy
{
NorthwindEntities ctx = new NorthwindEntities(u);
var q = from c in ctx.Suppliers select c;
foreach (var t in q)
{
Console.WriteLine(t.City);
}
///添加
var cust = new Customer()
{
CustomerID = "Test1",
Address = "Beijing",
City = "Peking",
CompanyName = "demo",
ContactName = "test",
ContactTitle = "mr.",
Country = "China",
Fax = "123",
Phone = "111",
PostalCode = "456",
Region = "HD"
};
ctx.AddToCustomers(cust);
ctx.SaveChanges();
///更新
var upCust = (from c in ctx.Customers where c.CustomerID == cust.CustomerID select c).FirstOrDefault();
upCust.ContactName += "-UPD";
ctx.UpdateObject(upCust);
ctx.SaveChanges();
///删除
upCust = (from c in ctx.Customers where c.CustomerID == cust.CustomerID select c).FirstOrDefault();
ctx.DeleteObject(upCust);
ctx.SaveChanges();
可见,在客户端可以使用LINQ语法进行查询
除了客户端,服务端也有很强的支持,下文再说。