0
votes

I am trying to sync data from an SQL Server to Dynamics CRM.

I had created a solution/project in C#. Where syncing an account entity of CRM, all the details like name, account number, ship date, phone number all this kind of detail are successfully syncing because form SQL, the data type is nvarchar or int and in CRM it is a single line of text.

But while I am doing the same sync from nvarchar to a lookup field of CRM it is not working and the exception occurs.

Here, the account is the name of the entity in CRM and SalesContact is name of the field from SQL and data type is nvarchar and ppg_salescontact is the name of the field in CRM and data type is lookup.

  Entity enAccount = new Entity("account");

 if (!String.IsNullOrEmpty(drRowAccount["SalesContact"] + "")) { enAccount["ppg_salescontact"] = 
 SecurityElement.Escape(drRowAccount["SalesContact"].ToString().Trim()); }

Exception :" Message : Error converting attribute value to Property: Attribute [ppg_salescontact], Attribute type [lookup] of Entity [account] with value of type [System.String]: [System.InvalidCastException: Unable to cast object of type 'System.String' to type 'Microsoft.Xrm.Sdk.EntityReference'. "

Please suggest me what can I do for this.

1
Did my answer help you solve your problem? if so, please mark it as accepted by ticking the V to its left. if not, let me know and I'll try to further help you.OfirD

1 Answers

1
votes

The exception you get says it all: You can't assign a value whose type is string to a field whose type is EntityReference.

So, to get an EntityReference based on that string, what you must do is take your string value, and based on this value, query the CRM to get the appropriate CRM record. Specifically, you need to query the CRM entity whose ppg_salescontact is the lookup for.

The result of this query would be of a type that derives from Entity, which you can then turn into EntityReference (by calling ToEntityReference()).

For example, if ppg_salescontact is a lookup for the CRM Contact entity, and if drRowAccount["SalesContact"] gives you the full name of the contact, then you can query it as follows (that's LINQ syntax):

Contact contact = orgContext
   .ContactSet
   .Where(c => c.FullName == drRowAccount["SalesContact"])
   .FirstOrDefault();
EntityReference contactRef = contact?.ToEntityReference();