I was trying to create a facility/equipment with the following code, but i'm getting an error saying "business unit id cannot be set to NULL"
I have only one business Unit created in my crm 2016 Here is my code:
string fetchBU = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='businessunit'>
<attribute name='name' />
<attribute name='address1_telephone1' />
<attribute name='websiteurl' />
<attribute name='parentbusinessunitid' />
<attribute name='businessunitid' />
<order attribute='name' descending='false' />
</entity>
</fetch>";
EntityCollection resultequipments = _orgService.RetrieveMultiple(new FetchExpression(fetchBU));
if (resultequipments.Entities.Count > 0)
{
Guid BuId;
BuId = (Guid)resultequipments.Entities[0]["businessunitid"];
Entity equipment = new Entity("equipment");
equipment["name"] = "test";
equipment["businessunitid"] = BuId;
_orgService.Create(equipment);
Console.WriteLine("Facility successfully created");
}
Thanks in advance.
The businessunitid
attribute in your query result is a primary key, i.e. Guid
type.
The businessunitid
attribute in an equipment
entity is a lookup, which is represented by an EntityReference
object.
You cannot assign a Guid
to an EntityReference
attribute. Modify your code similar to this:
EntityCollection businessUnits = _orgService.RetrieveMultiple(new FetchExpression(fetchBU));
if (businessUnits.Entities.Count > 0)
{
Entity equipment = new Entity("equipment");
equipment["name"] = "test";
equipment["businessunitid"] = new EntityReference("businessunit", businessUnits.Entities[0].Id);
_orgService.Create(equipment);
Console.WriteLine("Facility successfully created");
}