简体   繁体   中英

How to Sync data from SQL database field type(nvarchar) to Dynamics CRM field type (Lookup)

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM