Reputation: 1972
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
Reputation: 17552
Each one to many relationship has two important bits:
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