Retrieving related entities using RetrieveMultipleRequest - dynamics-crm

I have an entity called Invoice and an entity called InvoiceItem.
There is a one to many relationship called new_invoice_invoiceitem.
There is a LookupAttribute in InvoiceItem called new_parent_invoice_invoiceitem.
I am trying to retrieve the InvoiceItems that are related to the Invoice with a particular ID using the following code:
QueryExpression query = new QueryExpression();
query.EntityName = "new_invoiceitem";
query.ColumnSet = new AllColumns();
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "new_parent_invoice_invoiceitem";
condition.Values = new object [] { new Guid("fe1009cc-e034-49d5-bc59-ab4c3091a6f9") };
condition.Operator = ConditionOperator.Equal;
FilterExpression filter = new FilterExpression();
filter.AddCondition(condition);
query.Criteria = filter;
RetrieveMultipleRequest request = new RetrieveMultipleRequest();
request.Query = query;
RetrieveMultipleResponse response = (RetrieveMultipleResponse)crmService.Execute(request);
BusinessEntityCollection bec = response.BusinessEntityCollection;
The code runs without errors but the BusinessEntityCollection is always empty even though there are records in Dynamics.
Any idea what I'm doing wrong?
Thanks,
David

Try setting request.ReturnDynamicEntities = true

Related

ef6 linq method returning $ref for nested entries in query

my linq method system from EF6 is returning $ref when I monitor results in fiddler. If I watch the local window in my webapi everything is populated correctly, but not in the actual results that are returned. It only affects the nested entries. anyone know what I am doing wrong? (I created models from database in EF6)
var student = dbEF.Accounts
.Where(x => x.AccountNumber == acctNum)
.Select(x => new DTOCrmDetails()
{
AccountNumber = x.AccountNumber,
CommissionId = x.CommissionId,
Commission = x.Commission,
ManagerID = x.ManagerID,
ManagerName = x.Manager.ManagerName,
Manager = x.Manager,
Employees = x.Manager.Employees,
WireInstructionsUSD = x.Manager.WireInstructionsUSDs
//Mapping_ManagersExecutingBrokers = x.Manager.Mapping_ManagersExecutingBrokers
}).FirstOrDefault();
return student;
these are my settings.
var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
You need to disable your lazy loading in the entity framework dbcontext.
something like this way:
dbEF.Configuration.LazyLoadingEnabled = false;

CRM Linq find all parents that have 0 children

How can I find (preferably using CRM Linq) parent entities that have 0 children. For example how can I find all accounts that have 0 contacts.
If you are going to use the query expression route, which I would recommend then the following code will be useful
var entityAlias = "con";
var query = new QueryExpression
{
EntityName = "account",
ColumnSet = new ColumnSet(true),
Criteria =
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression(entityAlias, "contactid",ConditionOperator.Null)
}
}
LinkEntities =
{
new LinkEntity
{
EntityAlias = entityAlias,
LinkFromEntityName = "account",
LinkFromAttributeName = "accountid",
LinkToEntityName = "contact",
LinkToAttributeName = "parentcustomerid",
Columns = new ColumnSet("parentcustomerid", "contactid"),
JoinOperator = JoinOperator.LeftOuter,
}
},
};
var response = service.RetrieveMultiple(query);
var accounts = response.Entities;
In this code I have not limited the columns, this will reduce performance and you should only return the columns needed.
If there is the case for more than 5000 records are going to be returned then you will need to use paging and loop the query to find all the entities,
This can be found here:
https://msdn.microsoft.com/en-us/library/gg327917.aspx
However if you are certain you want to use LINQ then you can use the following code:
public static IEnumerable<Account> FindAccountsWithNoContacts()
{
var contactRelationship = new Relationship("contact_customer_accounts");
foreach(var account in XrmContext.AccountSet)
{
XrmContext.LoadProperty(contactRelationship);
if(!account.RelatedEntities.ContainsKey(contactRelationship)
yield return account;
}
}
My problem with the LINQ code is that all the enities, both the account and contact entities, will be loaded into memory. With large entity sets this can cause OutOfMemoryException, whereas the query expression route will pass the query to the Dynamics server to execute; which should make the execution of the code faster.
The thing you are looking for is left outer join. Which is unfortunately not possible in CRM using LINQ. However you can do it using query expression or FetchXML.
Here is a link that can help you:
https://community.dynamics.com/crm/b/gonzaloruiz/archive/2014/02/23/all-about-outer-join-queries-in-crm-2011-and-crm-2013

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?

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

Magento: Retrieve a list of Groups from a Attribute Set

I need to retrive a list of all groups of a certain attribute Set, given by the ID or name for example via API.
To do so, I've checked the API here (http://www.magentocommerce.com/api/soap/catalog/catalogProductAttributeSet/productAttributeSet.html) but it seems there's no way to list groups, only create, update and delete is possible.
What can I do to get the id of a certain group?
Thanks.
MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.catalogProductAttributeGroupRepositoryV1PortTypeClient mage_client= AttributeGroup;
MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.CatalogProductAttributeGroupRepositoryV1GetListRequest nn = new MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.CatalogProductAttributeGroupRepositoryV1GetListRequest();
MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.FrameworkFilter filter = new MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.FrameworkFilter();
MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.FrameworkFilter[] filters = new MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.FrameworkFilter[1];
filter.field = "attribute_set_id";
filter.value = "31";
filter.conditionType = "eq";
filters[0] = filter;
//MNC_Product_Sync.MagentoService.FrameworkFilter filter1 = new MNC_Product_Sync.MagentoService.FrameworkFilter();
MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.FrameworkSearchFilterGroup fg = new MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.FrameworkSearchFilterGroup();
fg.filters = filters;
MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.FrameworkSearchFilterGroup[] fgg = new MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.FrameworkSearchFilterGroup[1];
fgg[0] = fg;
MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.FrameworkSearchCriteriaInterface search = new MNC_Product_Sync.catalogProductAttributeGroupRepositoryV1Service.FrameworkSearchCriteriaInterface();
search.filterGroups = fgg;
search.pageSize = 100;
nn.searchCriteria = search;
try
{
var response = mage_client.catalogProductAttributeGroupRepositoryV1GetList(nn);
}

Is Dynamics CRM 2013 sdk cache result of QueryExpresions by Default?

I wrote this simple query:
var connectionString = String.Format("Url={0}; Username={1}; Password={2}; Domain={3}", url, username, password, domain);
var myConnection = CrmConnection.Parse(connectionString);
CrmOrganizationServiceContext _service = new CrmOrganizationServiceContext(myConnection);
var whoAmI = _service.Execute(new WhoAmIRequest());
var query = new QueryExpression
{
EntityName = "phonecall",
ColumnSet = new ColumnSet(true)
};
query.PageInfo = new PagingInfo
{
Count = 20,
PageNumber = 1,
PagingCookie = null
};
query.Orders.Add(new OrderExpression
{
AttributeName = "actualstart",
OrderType = OrderType.Descending
});
query.Criteria = new FilterExpression() { FilterOperator = LogicalOperator.And };
query.Criteria.AddCondition("call_caller", ConditionOperator.In, lines);
var entities = _service.RetrieveMultiple(query).Entities;
I have a program which runs this query every minute. On the first execution the correct results are displayed but for subsequent queries the results never change as I update records in CRM.
If I restart my program the results refresh correctly again on the first load.
Why are the results not updating as records are modified in CRM?
It is the CrmOrganizationServiceContext that is doing the caching - I found the following worked a treat and the results of my RetrieveMultiple are no longer cached :)
Context = new CrmOrganizationServiceContext(CrmConnection.Parse(connectionString));
Context.TryAccessCache(cache => cache.Mode = OrganizationServiceCacheMode.Disabled);
RetrieveMultiple always brings back fresh results so there must be some other aspect of your program which is causing stale data to be displayed.

Resources