Skip to main content

Notifications

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Unanswered

I need retrieve all contacts from one account

(0) ShareShare
ReportReport
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

  • Guido Preite Profile Picture
    54,077 Moderator 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
    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
    54,077 Moderator 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;
    	}
    }

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Jainam Kothari – Community Spotlight

We are honored to recognize Jainam Kothari as our June 2025 Community…

Congratulations to the May Top 10 Community Leaders!

These are the community rock stars!

Announcing the Engage with the Community forum!

This forum is your space to connect, share, and grow!

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Daivat Vartak (v-9davar) Profile Picture

Daivat Vartak (v-9d... 671 Super User 2025 Season 1

#2
Vahid Ghafarpour Profile Picture

Vahid Ghafarpour 167 Super User 2025 Season 1

#3
Muhammad Shahzad Shafique Profile Picture

Muhammad Shahzad Sh... 138 Most Valuable Professional

Product updates

Dynamics 365 release plans