1
votes

I have two custom entities with N:N relationship. 1) Membership , 2) Offer

I have used subgrid on form of Membership and Offer to shows related records.

I am writing one plugin function where I have one membership entity record id as input and I want to get all related records of Offer entity as output. I have tried following code but I couldn't get related offer entity records.

entity1 = "new_membership" , entity2 = "new_offer" , relationshipEntityName = "new_new_membership_new_offer"

public List<new_offer> getAllOffersFromMembership(string entity1,string entity2, string relationshipEntityName, string Id)
{
  QueryExpression query = new QueryExpression(entity1);    
  query.ColumnSet = new ColumnSet(true);    

  LinkEntity linkEntity1 = new LinkEntity(entity1, relationshipEntityName, "new_membershipid","new_membershipid", JoinOperator.Inner);    
  LinkEntity linkEntity2 = new LinkEntity(relationshipEntityName, entity2, "new_offerid","new_offerid", JoinOperator.Inner);
  linkEntity1.LinkEntities.Add(linkEntity2);
  query.LinkEntities.Add(linkEntity1);          

  linkEntity2.LinkCriteria = new FilterExpression();    
  linkEntity2.LinkCriteria.AddCondition(new ConditionExpression( “new_membershipid”, ConditionOperator.Equal, Id));

  EntityCollection collRecords = service.RetrieveMultiple(query);

  //To Do : Get offer entity records 
}

As I am new in MS CRM, may be I am doing some silly mistakes.

Thanks in advance.

1
What are the logical names of entity1, entity2 and relationshipEntityName?dynamicallyCRM
entity1 = new_membership, entity2 = new_offer, relationshipEntityName = "new_new_membership_new_offer"Sagar

1 Answers

2
votes

Invert your query to fetch related records.

var query = new QueryExpression("new_offer"){ColumnSet = new ColumnSet(true)};
var offerLinkEntity = new LinkEntity("new_offer", "new_new_membership_new_offer","new_offerid", "new_offerid", JoinOperator.Inner);

var memebershipLinkEntity = new LinkEntity("new_new_membership_new_offer", "new_membership","new_membershipid","new_membershipid", JoinOperator.Inner) {LinkCriteria = new FilterExpression()};

memebershipLinkEntity.LinkCriteria.AddCondition(new ConditionExpression("new_membershipid",ConditionOperator.Equal, mem.Id));

offerLinkEntity.LinkEntities.Add(memebershipLinkEntity);
query.LinkEntities.Add(offerLinkEntity);

var response = service.RetrieveMultiple(query);
var offers = response.Entities ?? Enumerable.Empty<new_offer>();