locked
create contact bound of account in CRM C# RRS feed

  • Question

  • I don't know how I can create a contact bound to an account. I have a csv file with an account and a contact, and I would like to import this data into my CRM. This is my code to add an account into CRM:

    #region Column One Mappings
    // Create a column mapping for a 'text' type field. Ajouter un Compte
    ColumnMapping colMapping1 = new ColumnMapping()
    {
        // Set source properties.
        SourceAttributeName = "my_new_accounts",
        SourceEntityName = "Account_1",
    
        // Set target properties.
        TargetAttributeName = "name",
        TargetEntityName = Account.EntityLogicalName,
    
        // Relate this column mapping with the data map.
        ImportMapId = new EntityReference(ImportMap.EntityLogicalName, importMapId),
    
        // Force this column to be processed.
        ProcessCode = new OptionSetValue((int)ColumnMappingProcessCode.Process)
    };
    
    // Create the mapping.
    Guid colMappingId1 = _serviceProxy.Create(colMapping1);
    #endregion

    Monday, July 10, 2017 2:24 PM

Answers

  • Hi Nina,

    Rather than creating an Account record, the code you posted appears to be for creating a part of a data map  which is something I personally have not done in code.

    Code to create an Account record (using the late bound programming model) might look something like this:

    var acct = new Entity();
    acct.LogicalName = "account";
    acct.Attributes["name"] = "Acme Corp";
    acct.Attributes["revenue"] = 10000000;
    service.Create(acct);

    Is there a requirement to automate the import of the CSV file?




    • Edited by Aron F Tuesday, July 11, 2017 9:41 PM
    • Marked as answer by BOUATMANE Wednesday, July 12, 2017 8:43 AM
    Tuesday, July 11, 2017 9:27 PM

All replies

  • Hi Nina,

    Rather than creating an Account record, the code you posted appears to be for creating a part of a data map  which is something I personally have not done in code.

    Code to create an Account record (using the late bound programming model) might look something like this:

    var acct = new Entity();
    acct.LogicalName = "account";
    acct.Attributes["name"] = "Acme Corp";
    acct.Attributes["revenue"] = 10000000;
    service.Create(acct);

    Is there a requirement to automate the import of the CSV file?




    • Edited by Aron F Tuesday, July 11, 2017 9:41 PM
    • Marked as answer by BOUATMANE Wednesday, July 12, 2017 8:43 AM
    Tuesday, July 11, 2017 9:27 PM
  • Hello Aron thank you for your answer,

    I have a csv file that contains accounts and contacts that I will have to save them in the crm
    At first, I managed to create accounts, but for the creation of the contacts I couldn't make it.

    this is my code how i created the account and how i tried to creat contact:

    #region Column One Mappings // Create a column mapping for a 'text' type field. Add the account ColumnMapping colMapping1 = new ColumnMapping() { // Set source properties. SourceAttributeName = "my_new_accounts", SourceEntityName = "Account_1", // Set target properties. TargetAttributeName = "name", TargetEntityName = Account.EntityLogicalName, // Relate this column mapping with the data map. ImportMapId = new EntityReference(ImportMap.EntityLogicalName, importMapId), // Force this column to be processed. ProcessCode = new OptionSetValue((int)ColumnMappingProcessCode.Process) }; // Create the mapping. Guid colMappingId1 = _serviceProxy.Create(colMapping1); #endregion

    //this code below doesn't work :'(

      Relationship accountContactRelationship = new Relationship("Account_1");
        EntityCollection contactCollection = new EntityCollection();
        contactCollection.EntityName = "contact";
           
          #region Column two Mappings
          // Create a column mapping for a 'text' type field. **Ajouter un Contact**
          ColumnMapping colMapping3 = new ColumnMapping()
          {
              // Set source properties.
              SourceAttributeName = "Nom",
              SourceEntityName = "Account_1",

              // Set target properties.
              TargetAttributeName = "address3_name",
              TargetEntityName = Contact.EntityLogicalName,

              // Relate this column mapping with the data map.
              ImportMapId =
                new EntityReference(ImportMap.EntityLogicalName, importMapId),

                      // Force this column to be processed.
                      ProcessCode =
                          new OptionSetValue((int)ColumnMappingProcessCode.Process)
                  };

                  // Create the mapping.
                  Guid colMappingId3 = _serviceProxy.Create(colMapping3);
             //   contactCollection.Entities.Add(contact);
             //   colMapping1.RelatedEntities[accountContactRelationship] = contactCollection;
               #endregion

    For each contact I have to bind it to an account, we can have 3 contact that must be bind to an account.

    Best regards



    • Edited by BOUATMANE Wednesday, July 12, 2017 9:23 AM
    Wednesday, July 12, 2017 9:07 AM
  • To associate a Contact to an Account requires setting the Account lookup on the Contact record. We do this with an instance of the Entity Reference class:

    Contact contact = new Entity();
    
    contact.Attributes["firstname"] = "Jane"; 
    
    contact.Attributes["lastname"] = "Doe"; 
    
    contact.Attributes["accountid"] = new EntityReference("account", new Guid("D1C4CD52-1E51-E711-8122-6C3BE5B3B698")); 
    

    Wednesday, July 12, 2017 7:43 PM
  • hello, thnak you for answer,

    I tested this code, but it doesn't work :( 

    The account saved successfully, but the contacts

    
    Entity contact = new Entity();
                 contact = new Contact
                {
                    FirstName = "John",
                    LastName = "Doe"
                };



    contact.Attributes["Account_1"] = new EntityReference("account", colMappingId1);

    Thursday, July 13, 2017 2:14 PM
  • In this line of code,

    contact.Attributes["Account_1"] = new EntityReference("account", colMappingId1)

    "Account_1" has to be the name of the lookup field, i.e. "new_accountid", and the colMappingId1 has to be the Guid of the Account to which you want to relate the contacts.

    Thursday, July 13, 2017 2:28 PM
  • "Account_1" is an EntityLogicalName in my code 
    Tuesday, July 18, 2017 11:37 AM
  • The code to set the out-of-box customer field for a Contact would be:

    contact.Attributes["parentcustomerid"] = new EntityReference("account", new Guid("D1C4CD52-1E51-E711-8122-6C3BE5B3B698"))

    with the Guid being the ID of the account.

    Tuesday, July 18, 2017 12:49 PM
  • thank you Aron, but my problem is about mapping, please try to understund my code.

    I have csv file and i do importation of data using sample sdk, and my probleme is how to use two entities (account/contact) in maping.

    my file csv is look like the link below: 

    https://blogs.msdn.microsoft.com/crm/2010/11/04/importing-two-or-more-entities-from-a-single-file/

           public void ImportRecords()
            {
                // Create an import map.
                ImportMap importMap = new ImportMap()
                {
                    Name = "Import Map " + DateTime.Now.Ticks.ToString(),
                    Source = "Import Accounts.csv",
                    Description = "Import  accounts/Contacts",
                    EntitiesPerFile =
                        new OptionSetValue((int)ImportMapEntitiesPerFile.SingleEntityPerFile),
                    EntityState = EntityState.Created
                };
                Guid importMapId = _serviceProxy.Create(importMap);


                    // Create column mappings.

                    #region Column One Mappings
                    // Create a column mapping for a 'text' type field. **Ajouter un Compte**
                    ColumnMapping colMapping1 = new ColumnMapping()
                    {
                        // Set source properties.
                        SourceAttributeName = "Nom_Societe",
                        SourceEntityName = "Account_1",

                        // Set target properties.
                        TargetAttributeName = "name",
                        TargetEntityName = Account.EntityLogicalName,

                        // Relate this column mapping with the data map.
                        ImportMapId =
                            new EntityReference(ImportMap.EntityLogicalName, importMapId),

                        // Force this column to be processed.
                        ProcessCode =
                            new OptionSetValue((int)ColumnMappingProcessCode.Process)
                    };

                // Create the mapping.
                Guid colMappingId1 = _serviceProxy.Create(colMapping1);
                    #endregion


            // her i think that i must to use lookup but i don't knwo how i can do this


                  #region Column two Mappings
                   // Create a column mapping for a 'text' type field. **Ajouter un Contact**
                   ColumnMapping colMapping3 = new ColumnMapping()
                   {
                       // Set source properties.
                       SourceAttributeName = "Nom",
                       SourceEntityName = "Account_1",

                       // Set target properties.
                       TargetAttributeName = "address3_name",
                       TargetEntityName = Contact.EntityLogicalName,

                       // Relate this column mapping with the data map.
                       ImportMapId =
                           new EntityReference(ImportMap.EntityLogicalName, importMapId),

                       // Force this column to be processed.
                       ProcessCode =
                           new OptionSetValue((int)ColumnMappingProcessCode.Process)
                   };

                   // Create the mapping.
                   Guid colMappingId3 = _serviceProxy.Create(colMapping3);
                 #endregion
                 


    when i run my program i get this message : this source entity is mapped to more than one microsoft dynamics 365 entity

    • Edited by BOUATMANE Tuesday, July 18, 2017 2:52 PM
    Tuesday, July 18, 2017 1:54 PM
  • Hi,

    This article seems to be a pretty good example for what you're trying to do, including mapping a lookup value. For reference, below is the sample code for the lookup piece. You might want to get the example running first, then adapt it to your specific columns.

    As it seems that it's adds a lot of complexity to create the map on the fly in code, you might want to consider the approach of creating the data map in the UI (rather than in code) then retrieve and use it when you do the import. This article might be helpful for that approach.

    #region Column Two Mappings
    // Create a column mapping for a 'lookup' type field.
    ColumnMapping colMapping2 = new ColumnMapping()
    {
    	// Set source properties.
    	SourceAttributeName = "src_parent",
    	SourceEntityName = "Account_1",
    
    	// Set target properties.
    	TargetAttributeName = "parentaccountid",
    	TargetEntityName = Account.EntityLogicalName,
    
    	// Relate this column mapping with the data map.
    	ImportMapId =
    		new EntityReference(ImportMap.EntityLogicalName, importMapId),
    
    	// Force this column to be processed.
    	ProcessCode =
    		new OptionSetValue((int)ColumnMappingProcessCode.Process),
    };
    
    // Create the mapping.
    Guid colMappingId2 = _serviceProxy.Create(colMapping2);
    
    // Because we created a column mapping of type lookup, we need to specify lookup details in a lookupmapping.
    // One lookupmapping will be for the parent account, and the other for the current record.
    // This lookupmapping is important because without it the current record
    // cannot be used as the parent of another record.
    
    // Create a lookup mapping to the parent account.  
    LookUpMapping parentLookupMapping = new LookUpMapping()
    {
    	// Relate this mapping with its parent column mapping.
    	ColumnMappingId =
    		new EntityReference(ColumnMapping.EntityLogicalName, colMappingId2),
    
    	// Force this column to be processed.
    	ProcessCode =
    		new OptionSetValue((int)LookUpMappingProcessCode.Process),
    
    	// Set the lookup for an account entity by its name attribute.
    	LookUpEntityName = Account.EntityLogicalName,
    	LookUpAttributeName = "name",
    	LookUpSourceCode =
    		new OptionSetValue((int)LookUpMappingLookUpSourceCode.System)
    };
    
    // Create the lookup mapping.
    Guid parentLookupMappingId = _serviceProxy.Create(parentLookupMapping);
    
    // Create a lookup on the current record's "src_name" so that this record can
    // be used as the parent account for another record being imported.
    // Without this lookup, no record using this account as its parent will be imported.
    LookUpMapping currentLookUpMapping = new LookUpMapping()
    {
    	// Relate this lookup with its parent column mapping.
    	ColumnMappingId =
    		new EntityReference(ColumnMapping.EntityLogicalName, colMappingId2),
    
    	// Force this column to be processed.
    	ProcessCode =
    		new OptionSetValue((int)LookUpMappingProcessCode.Process),
    
    	// Set the lookup for the current record by its src_name attribute.
    	LookUpAttributeName = "src_name",
    	LookUpEntityName = "Account_1",
    	LookUpSourceCode =
    		new OptionSetValue((int)LookUpMappingLookUpSourceCode.Source)
    };
    
    // Create the lookup mapping
    Guid currentLookupMappingId = _serviceProxy.Create(currentLookUpMapping);
    #endregion




    • Edited by Aron F Wednesday, July 19, 2017 1:05 PM
    Wednesday, July 19, 2017 1:04 PM
  • thank you, I tried to use this but i get many error, this is my new code :

        // Create column mappings.

               #region Column One Mappings
                    // Create a column mapping for a 'text' type field. **Ajouter un Compte**
                    ColumnMapping colMapping1 = new ColumnMapping()
                    {
                        // Set source properties.
                        SourceAttributeName = "Nom_Societe",
                        SourceEntityName = "Account_1",

                        // Set target properties.
                        TargetAttributeName = "name",
                        TargetEntityName = Account.EntityLogicalName,

                        // Relate this column mapping with the data map.
                        ImportMapId =
                            new EntityReference(ImportMap.EntityLogicalName, importMapId),

                        // Force this column to be processed.
                        ProcessCode =
                            new OptionSetValue((int)ColumnMappingProcessCode.Process)
                    };

                    // Create the mapping.
                    Guid colMappingId1 = _serviceProxy.Create(colMapping1);
                 #endregion


                 #region Column One Mappings
                    // Create a column mapping for a 'text' type field. **Ajouter le nom domaine de Compte**
                    ColumnMapping colMapping2 = new ColumnMapping()
                    {
                        // Set source properties.
                        SourceAttributeName = "Domaine_societe",
                        SourceEntityName = "Account_1",

                        // Set target properties.
                        TargetAttributeName = "websiteurl",
                        TargetEntityName = Account.EntityLogicalName,

                        // Relate this column mapping with the data map.
                        ImportMapId =
                            new EntityReference(ImportMap.EntityLogicalName, importMapId),

                        // Force this column to be processed.
                        ProcessCode =
                            new OptionSetValue((int)ColumnMappingProcessCode.Process)
                    };

                    // Create the mapping.
                    Guid colMappingId2 = _serviceProxy.Create(colMapping2);
                #endregion

                #region Column One Mappings
                // Create a column mapping for a 'text' type field. **Ajouter le nom adresse mail de Compte**
                ColumnMapping colMapping4 = new ColumnMapping()
                {
                    // Set source properties.
                    SourceAttributeName = "Email",
                    SourceEntityName = "Account_1",

                    // Set target properties.
                    TargetAttributeName = "emailaddress1",
                    TargetEntityName = Account.EntityLogicalName,

                    // Relate this column mapping with the data map.
                    ImportMapId =
                        new EntityReference(ImportMap.EntityLogicalName, importMapId),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)ColumnMappingProcessCode.Process)
                };



                // Create the mapping.
                Guid colMappingId4 = _serviceProxy.Create(colMapping4);
                #endregion

                #region Column two Mappings
                // Create a column mapping for a 'text' type field. **Ajouter un Contact**
                ColumnMapping colMapping3 = new ColumnMapping()
                   {
                       // Set source properties.
                       SourceAttributeName = "Nom",
                       SourceEntityName = "Account_1",

                       // Set target properties.
                       TargetAttributeName = "address3_name",
                       TargetEntityName = Contact.EntityLogicalName,

                       // Relate this column mapping with the data map.
                       ImportMapId =
                           new EntityReference(ImportMap.EntityLogicalName, importMapId),

                       // Force this column to be processed.
                       ProcessCode =
                           new OptionSetValue((int)ColumnMappingProcessCode.Process)
                   };

                   // Create the mapping.
                   Guid colMappingId3 = _serviceProxy.Create(colMapping3);
              //  #endregion

                //*********************************** Lookup ************************************************
                // Create a lookup mapping to the parent account.  
                LookUpMapping parentLookupMapping = new LookUpMapping()
                {
                    // Relate this mapping with its parent column mapping.
                    ColumnMappingId =
                        new EntityReference(ColumnMapping.EntityLogicalName, colMappingId3),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)LookUpMappingProcessCode.Process),

                    // Set the lookup for an account entity by its name attribute.
                    LookUpEntityName = Account.EntityLogicalName,
                    LookUpAttributeName = "name",
                    LookUpSourceCode =
                        new OptionSetValue((int)LookUpMappingLookUpSourceCode.System)
                };

                // Create the lookup mapping.
                Guid parentLookupMappingId = _serviceProxy.Create(parentLookupMapping);

                // Create a lookup on the current record's "src_name" so that this record can
                // be used as the parent account for another record being imported.
                // Without this lookup, no record using this account as its parent will be imported.
                LookUpMapping currentLookUpMapping = new LookUpMapping()
                {
                    // Relate this lookup with its parent column mapping.
                    ColumnMappingId =
                        new EntityReference(ColumnMapping.EntityLogicalName, colMappingId3),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)LookUpMappingProcessCode.Process),

                    // Set the lookup for the current record by its src_name attribute.
                    LookUpAttributeName = "src_name",
                    LookUpEntityName = "Account_1",
                    LookUpSourceCode =
                        new OptionSetValue((int)LookUpMappingLookUpSourceCode.Source)
                };

                // Create the lookup mapping
                Guid currentLookupMappingId = _serviceProxy.Create(currentLookUpMapping);
                #endregion
                //**************************************ADD Relationship*********************************************

                //create the query expression object
                QueryExpression query = new QueryExpression();

                //Query on reated entity records
                query.EntityName = "contact";

                //Retrieve the all attributes of the related record
                query.ColumnSet = new ColumnSet(true);

                //create the relationship object
                Relationship relationship = new Relationship();

                //add the condition where you can retrieve only the account related active contacts
                query.Criteria = new FilterExpression();
                query.Criteria.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, "Active"));

                // name of relationship between account & contact
                relationship.SchemaName = "contact_customer_accounts";

                //create relationshipQueryCollection Object
                RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

                //Add the your relation and query to the RelationshipQueryCollection
                relatedEntity.Add(relationship, query);

                //create the retrieve request object
                RetrieveRequest request = new RetrieveRequest();

                //add the relatedentities query
                request.RelatedEntitiesQuery = relatedEntity;

                //set column to  and the condition for the account
                request.ColumnSet = new ColumnSet("name");
                request.Target = new EntityReference { Id = colMappingId1, LogicalName = "account" };

                //execute the request
                RetrieveResponse response = (RetrieveResponse)_serviceProxy.Execute(request);
                //*****************************************************************************************


    • Edited by BOUATMANE Friday, July 21, 2017 11:52 AM
    Friday, July 21, 2017 8:38 AM
  • Hi, you would have to post each error you're getting with the corresponding line of code where it happens.

    In addition to debugging as a console app, you might want to consider testing your file by mapping and importing it via the UI.

    Tuesday, July 25, 2017 10:38 AM