Dynamics CRM2016 WebApi之alternate key的更新与删除

时间:2021-11-03 07:24:49

    之前已有篇博文介绍了web api 利用alternate key来查询数据,最近有人问起,是否可以利用alternate key来更新和删除数据呢,查询SDK后并没有发现说支持这样做,那就需要实践下了。

   比如通过如下示例代码将客户名称为DTCC的记录中的地址字段从"北京"改成"上海"(前提是设置accout的name字段为alternate key

 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.
Create("http://121.40.75.24:5555/origin/api/data/v8.0/accounts(name='DTCC')");
req.Credentials = new NetworkCredential("admin", "pwd", "skysoft");
req.Method = "patch";
req.Accept = "application/json";
req.ContentType = "application/json; charset=utf-8";
byte[] data = Encoding.UTF8.GetBytes("{\"new_address\":\"上海\"}");
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
StreamReader read = new StreamReader(res.GetResponseStream());
string result = read.ReadToEnd();
}
Dynamics CRM2016 WebApi之alternate key的更新与删除

   运行后发现,结果是成功的,再比如我们把request的method换成put来更新单个字段,再改回"北京",运行后结果是正确的。

 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.                Create("http://121.40.75.24:5555/origin/api/data/v8.0/accounts(name='DTCC')/new_address");            req.Credentials = new NetworkCredential("admin", "pwd", "skysoft");            req.Method = "put";            req.Accept = "application/json";            req.ContentType = "application/json; charset=utf-8";            byte[] data = Encoding.UTF8.GetBytes("{\"value\":\"北京\"}");            Stream newStream = req.GetRequestStream();            newStream.Write(data, 0, data.Length);            newStream.Close();            using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())            {                StreamReader read = new StreamReader(res.GetResponseStream());                string result = read.ReadToEnd();            }
   当然在尝试过删除单个字段和删除记录后,证实删除也是可以的。