Skip to main content

Notifications

Announcements

No record found.

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
    Guido Preite 54,073 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
    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,073 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

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 292,516 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,409 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans