web
You’re offline. This is a read only version of the page.
close
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

I have the same question (0)
  • 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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 108 Super User 2025 Season 2

#2
Jimmy Passeti Profile Picture

Jimmy Passeti 50 Most Valuable Professional

#3
Gerardo Rentería García Profile Picture

Gerardo Rentería Ga... 49 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans