如何检索与 ms crm 插件中的第一个实体有 n:n 关系的第二个实体的多个记录(包含所有字段)?

how to retrieve multiple records (with all fields) of second entity which has n:n relationship with first entity in plug in in ms crm?

我有两个具有 N:N 关系的自定义实体。 1) 会员资格,2) 优惠

我在Membership和Offer的表格中使用了subgrid来显示相关记录。

我正在编写一个插件函数,其中我有一个成员资格实体记录 ID 作为输入,我想获取报价实体的所有相关记录作为输出。 我尝试了以下代码,但我无法获取相关的报价实体记录。

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 
}

由于我是 MS CRM 的新手,可能是我犯了一些愚蠢的错误。

提前致谢。

反转查询以获取相关记录。

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>();