Daily Archives: November 21, 2012

Retrieve primary entity and related entity data using OData in MS CRM 2011

Are you looking to access primary entity and related entity data in single query using OData then this post is for you.

If we need to access related entity data, we can use expend open in our odata query, we need to specify relationship name, in below example I am fetching data from account and more address entity and relationship name for this is “Account_CustomerAddress”. Here is the code to get entity information:

function GetRelated() {
var context = Xrm.Page.context;
var EntityID = Xrm.Page.data.entity.getId();
var serverUrl = context.getServerUrl();
var ODataPath = serverUrl + “/XRMServices/2011/OrganizationData.svc”;
var retrieveResult = new XMLHttpRequest();
retrieveResult.open(“GET”, ODataPath + “/AccountSet?$filter=AccountId eq (guid'” + EntityID + “‘)&$expand=Account_CustomerAddress”, false);
retrieveResult.setRequestHeader(“Accept”, “application/json”);
retrieveResult.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
if (retrieveResult.readyState == 4 /* complete */) {
if (retrieveResult.status == 200) {
var retrieved= this.parent.JSON.parse(retrieveResult.responseText).d;
var Result = retrieved.results[0];
//Field From Account
//fields from more address


Hope it will help.

Note: if you will copy this code please make sure to change quotes.


Filed under MS CRM 2011