I am new to not only C#, but also Microsoft Dynamics and I am having difficult accessing parent entity data of my Contact via a plug in. My goal is to auto fill my contact's address with the parent account address if the contact address fields are empty. I feel this is a relatively simple process that I am over complicating it.
public void SetContactAddress()
{
// TODO: Go and get the contact's parent account record and retrieve the
// address fields. Then update the contact's address with the fields from the
// values from the account. Do not overrride the contact's address if one is provided/exists
var item = _baseModel.TargetEntity as Entity;
var parent = _baseModel.TargetEntity as Entity;
Contact contact = new Contact(); //New blank contact in memory
contact.Id = item.Id; //assign Id to the new local contact
var service = _targetContact as IOrganizationService;
Guid parentId = ((EntityReference)contact["new_parentid"]).Id;
Entity parentEntity = service.Retrieve("new_parent", parentId, new ColumnSet(true)); //retrieve parent entity
string[] addressAtrributes = {"Address1_City","Address1_Country","Address1_Line1","Address1_Line2",
"Address1_Line3", "Address1_PostalCode","Address1_StateOrProvince"};
foreach (var key in parentEntity.Attributes.Keys)
{
if (addressAtrributes.Contains(key))
{
//contact.Address1_City = key;
contact[key] = key;
}
}
//contact.Address1_City = "My City"; //I can easily hard code a city in
_baseModel.OrganizationService.Update(contact);
}