LINQPad – D365 Connections

You can create connections to Dynamics 365 (CRM 2016 etc) without using the LINQPad CRM Driver.

  1. Create a new query
  2. Select Query | References and Properties from the menu (F4)
  3. Add the following references to the Query Properties
  4. linqpad-d365-1
  5. If you have an assembly with Early Bound entities you can also add it here.
  6. Open the Additional Namespace Imports tab and select the following namespaces. Include any Early Bound entity namespaces here too.
  7. linqpad-d365-2
  8. Enter the following code into LINQPad to make your connection and generate your queries.
  9. The Util.GetPassword is the LINQPad utility method for retrieving a password encrypted in the LINQPad Password Manager.
void Main()
{
 string url = "https://mycompany.crm6.dynamics.com"; 
 string username = "mycompany.user@mycompany.onmicrosoft.com";
 string password = Util.GetPassword("d365-crmadmin");
 
 CrmServiceClient conn = new CrmServiceClient($"Url={url};Username={username};Password={password}; AuthType=Office365");

conn.OrganizationServiceProxy.Timeout = new System.TimeSpan(0, 3, 0);
 
 conn.OrganizationServiceProxy.EnableProxyTypes();
 
 IOrganizationService orgService = conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

Context = new XrmServiceContext(orgService);

// Write your queries as normal
 // var myQuery = from a in Context.AccountSet where ....
}

public XrmServiceContext Context { get; set; }

 

Advertisements

ForeignKeyReferenceAlreadyHasValueException

Updating a Foreign Key value using LINQ
 

Table A has a Foreign Key (integer) field that is referencing a Primary Key (integer) field in Table B. I wanted to be able to set the value of the integer in Table A to a new value using my entity object property for Table A. When I tried to set the value of the integer field I got a ForeignKeyReferenceAlreadyHasValueException and the message ‘Operation is not valid due to the current state of the object.’

The solution is not to try and set the integer value of the field but define the value for the whole entity. For example;

// Dont assign just the ID value

EntityName.ForeignKeyFieldID = myIntegerValue;

// Assign the entity

EntityName.ForeignKeyField = myEntity;