web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
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,086 Moderator on at

    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;
    	}
    }

  • anteOjo Profile Picture
    20 on at

    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,086 Moderator on at

    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.

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

Season of Sharing Community Challenge Winners!

Congratulations to our community stars!

Women in Power Builds Momentum

Expanding mentorship, skilling, and AI innovation

Congratulations to the August Top 10 Community Leaders

These are the community rock stars!

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Syed Aqib Raza Profile Picture

Syed Aqib Raza 125

#2
ParthPatel249 Profile Picture

ParthPatel249 87

#3
11manish Profile Picture

11manish 85 Super User 2026 Season 2

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans