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 =;
var serverUrl = context.getServerUrl();
var ODataPath = serverUrl + “/XRMServices/2011/OrganizationData.svc”;
var retrieveResult = new XMLHttpRequest();“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

6 responses to “Retrieve primary entity and related entity data using OData in MS CRM 2011

  1. Milan Hingu

    Hello Mahneder Pal,

    I am using your code .. Kept eye on your Note.(Change quote)
    All working fine..
    My primary entity is Order and related entity is Product (1 Order : N Product).

    I have used below url..

    var url = ODataPath + “/OrderSet?$filter=salesorderid eq (guid’” + EntityID + “‘)&$expand=order_details”;

    But i am getting 404: Not Found.

    Is anything wrong in url ?

  2. rahul

    thank u so much sir

  3. Very good post. This helped med a lot, I really didn’t want to do a fetchxml-query with js.

  4. safna

    How to get the id of a primary entity in related entity. For eg how to get order ID in order Product ID.

    • mahenderpal

      I hope you are asking to get it in Client side, you you can simply write below script in your order product form

      var ID = Xrm.Page.getAttribute(“orderid”).getValue();

      But make sure you have updated rollup installed because initially there was issue (which is fixed), where you will get this order id only when order product is created

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s