Dynamics CRM2016 WebApi之alternate key的更新與刪除

vic0228發表於2017-06-21

    之前已有篇博文介紹了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();
            }

   執行後發現,結果是成功的,再比如我們把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();
            }
   當然在嘗試過刪除單個欄位和刪除記錄後,證實刪除也是可以的。

相關文章