rsteckly
rsteckly

Reputation: 1972

How do you reference a one to many relationship in CRMService?

I have a custom entity with a one to many relationship (reference, non parental) defined in Dynamics. I'm using CRMService. I've published my changes and updated the webservice reference in my project.

How do I access this relationship in my code? How do you use CRMService code to reference a relationship?

I've found some code for many-to-many and understand that is difficult, but what about one to many?

Thanks!

Upvotes: 1

Views: 1644

Answers (1)

James Wood
James Wood

Reputation: 17552

Each one to many relationship has two important bits:

  1. A name - this isnt used as often but for example contact has a relationship to account which represents the primary contact for the account, the name of this is "account_primary_contact".
  2. A field on the many entity (the foreign key), in the case of the primary contact this is "primarycontactid".

Theres three main things things you can do with a one to many relationship (note, I'm using the late bound entities in my examples here, I will be using the primary contact relationship in my snippets).

1. Create a link between two records

Basically you just populate the foreign key with the Id of the thing you want to link to.

//Create a contact
Guid contactId = service.Create(new DynamicEntity("contact"));

//Create a lookup which we will use to link the contact and account
Lookup lookup = new Lookup();
lookup.Value = contactId;
lookup.type = "contact";

//Create an account which is linked to the contact record
DynamicEntity account = new DynamicEntity("account");
account["name"] = "Test Account";
account["primarycontactid"] = lookup;
Guid accountId = service.Create(account);

2. Find out what records are linked by those relationships

So this is a case of creating a QueryExpression which either uses LinkEntities:

LinkEntity link = new LinkEntity();
link.LinkFromEntityName = "contact";
link.LinkFromAttributeName = "contactid";
link.LinkToEntityName = "account";
link.LinkToAttributeName = "primarycontactid";

Or a ConditionExpression which filters the related records to those linked to your primary record.

ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "primarycontactid";
condition.Operator = ConditionOperator.Equal;
condition.Values = new string [] { contactId.ToString() };

Full examples on the MSDN.

3. Break the link between two records

So this is achieved by setting the foreign key to null.

DynamicEntity account = new DynamicEntity("account");
account["primarycontactid"] = null;
service.Update(account);

Upvotes: 1

Related Questions