Search code examples
c#dynamics-crm

Best way to pass a Lookup GUID while creating a new Opportunity entity


I have a MVC form that features an @Html.TextBox that I use as a search box. My user can get a list of options built from the data returned by CRM when they click the search button. I'm capturing the GUID of the selected item... a good thing.

How do I format the data?

When my user submits the form, how do I format the GUID so the Opportunity entity being created can assign the selected GUID to the Lookup field (associated with a Contact)?

What follows is a brief example of how I'm doing the submission to CRM. I'm submitting 70+ fields worth of data. The Picklist, DateTime, String fields all of them work, it's just the Lookup fields I can't make it work yet.

OrganizationServiceClient client = new OrganizationServiceClient();
Microsoft.Xrm.Sdk.Entity ec = new Entity {
    LogicalName = "opportunity"
};
ec.Attributes.Add(new KeyValuePair<string, object>("name", Request.Form["newOppName"]));
ec.Attributes.Add(new KeyValuePair<string, object>("org_managers", Request.Form["selectedGUID"]));
// "org_managers" name for Lookup (simple; dependent on Contact) within Opportunity entity
var OppGUID = await client.CreateAsync(ec);

I've tried a couple of other methods that are rooted in JavaScript rather than C#, but nothing works.


Solution

  • It’s called EntityReference. It should get assigned like below:

    ec[“org_managers”] = new EntityReference(“contact”, new Guid(Request.Form["selectedGUID"]));
    

    Or

    ec.Attributes[“org_managers”] = new EntityReference(“contact”, new Guid(Request.Form["selectedGUID"]));
    

    Or

    ec.Attributes.Add(“org_managers”, new EntityReference(“contact”, new Guid(Request.Form["selectedGUID"]));