Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM forum
Unanswered

I need retrieve all contacts from one account

Posted on by 20

Hello ... I need retrieve all contacts from one account

I do this and don´t work

I need help please

public List CargarUsuarios(Guid queCuenta)
        {
            
            using (OrganizationService service = new OrganizationService("NubitCrmNav"))
            {
                //Microsoft.Xrm.Sdk.EntityReference accountId = new Microsoft.Xrm.Sdk.EntityReference("account", queCuenta);
                QueryExpression query = new QueryExpression("contact");
                query.ColumnSet.AddColumns("contactid", "fullname","accountid");

                string strGuid = queCuenta.ToString();
                Guid gEmpresa = Guid.Parse(strGuid);

                ConditionExpression empresa = new ConditionExpression();
                empresa.AttributeName = "accountid"; // "accountid";
                empresa.Operator = ConditionOperator.Equal;
                empresa.Values.Add(gEmpresa);

                query.LinkEntities.Add(new LinkEntity("contact", "account", "accountid", "accountid", JoinOperator.LeftOuter));
                query.LinkEntities[0].Columns.AddColumns("accountid");
                query.LinkEntities[0].EntityAlias = "empresa";
                /*query.LinkEntities.Add(new LinkEntity("account", "contact", "contactid", "contactid", JoinOperator.LeftOuter));
                query.LinkEntities[1].Columns.AddColumns("fullname", "contactid", "accountid");
                query.LinkEntities[1].EntityAlias = "contacto";*/

                query.Orders.Add(new OrderExpression("fullname", OrderType.Ascending));
                query.Distinct = true;
                List usuarios = new List();
                System.Net.ServicePointManager.SecurityProtocol = tls12;
                EntityCollection usuariosRecord = service.RetrieveMultiple(query);

                if (usuariosRecord != null && usuariosRecord.Entities.Count > 0)
                {
                    ContactEntityModels usuariosModel;
                    for (int i = 0; i < usuariosRecord.Entities.Count; i  )
                    {
                        usuariosModel = new ContactEntityModels();
                        if (usuariosRecord[i].Contains("contactid") && usuariosRecord[i]["contactid"] != null)
                            usuariosModel.ContactID = (Guid)(usuariosRecord[i]["contactid"]);
                        if (usuariosRecord[i].Contains("accountid") && usuariosRecord[i]["accountid"] != null)
                            usuariosModel.AccountID = (Guid)((AliasedValue)usuariosRecord[i]["empresa.accountid"]).Value;
                        if (usuariosRecord[i].Contains("fullname") && usuariosRecord[i]["fullname"] != null)
                            usuariosModel.NombreCompleto = usuariosRecord[i]["fullname"].ToString();
                        usuarios.Add(usuariosModel);
                    }
                }
                return usuarios;
            }
        }

Account no filter

Categories:
  • Guido Preite Profile Picture
    Guido Preite 54,057 Super User on at
    RE: I need retrieve all contacts from one account

    the error you wrote doesn't come from the code you posted and the one I wrote. Because that kind of error (System.InvalidCastException with Contact object) can happen if you have added Early Bound generated classes and you use that classes, but nowhere in the code that kind of classes are used.

    If you are not able to fix this kind of logic try to find someone to assist you, I see it difficult that posting code and errors inside this forum can help you solve the issues you are facing.

  • anteOjo Profile Picture
    anteOjo 20 on at
    RE: I need retrieve all contacts from one account

    Error

    No se puede convertir un objeto de tipo 'Contact' al tipo 'Entity'.

    Descripción: Excepción no controlada al ejecutar la solicitud Web actual. Revise el seguimiento de la pila para obtener más información acerca del error y dónde se originó en el código.

    Detalles de la excepción: System.InvalidCastException: No se puede convertir un objeto de tipo 'Contact' al tipo 'Entity'.

    Error de código fuente:

    Línea 162:                List<ContactEntityModels> usuarios = new List<ContactEntityModels>();

    Línea 163:

    Línea 164:                foreach (Entity usuarioRecord in usuariosRecord.Entities)

    Línea 165:                {

    Línea 166:                    ContactEntityModels usuariosModel = new ContactEntityModels();

  • Guido Preite Profile Picture
    Guido Preite 54,057 Super User on at
    RE: I need retrieve all contacts from one account

    this code should work, I removed all the unnecessary code from the one you posted

    public List CargarUsuarios(Guid queCuenta)
    {          
    	using (OrganizationService service = new OrganizationService("NubitCrmNav"))
    	{
    		QueryExpression query = new QueryExpression("contact");
    		query.ColumnSet = new ColumnSet("fullname", "accountid");
    		query.Criteria.AddCondition("accountid", ConditionOperator.Equal, queCuenta);
    		query.AddOrder("fullname", OrderType.Ascending);
    		EntityCollection usuariosRecord = service.RetrieveMultiple(query);
    		
    		List usuarios = new List();
    	
    		foreach(Entity usuarioRecord in usuariosRecord.Entities) {
    			ContactEntityModels usuariosModel = new ContactEntityModels();
    			usuariosModel.ContactID = usuarioRecord.Id;
    			usuariosModel.AccountID = queCuenta;
    			usuariosModel.NombreCompleto = usuarioRecord.GetAttributeValue("fullname");
    			usuarios.Add(usuariosModel);
    		}
    		
    		return usuarios;
    	}
    }

Helpful resources

Quick Links

Replay now available! Dynamics 365 Community Call (CRM Edition)

Catch up on the first D365 Community Call held on 7/10

Community Spotlight of the Month

Kudos to Saurav Dhyani!

Congratulations to the June Top 10 community leaders!

These stars go above and beyond . . .

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 287,995 Super User

#2
Martin Dráb Profile Picture

Martin Dráb 225,610 Super User

#3
nmaenpaa Profile Picture

nmaenpaa 101,148

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans