When deploying solutions, you can’t include Business Units in your solution file and if you are needing to create many of them, this can be a bit of a hassle.
I recently had this problem where I was working on a project that had many units that I didn’t want to create manually, so I turned my eyes to the SDK in order to take this task from 20 minutes to 1.
The Parent Business Unit
The most important thing with Business Units is to remember their hierarchy. Irrespective of how you have setup your system, you will always have a top-level unit that everything else inherits from.
When trying to find this unit (to then extend from) all you need to do is query for the businessunit that does not have a parent and this will be it.
QueryExpression exp = new QueryExpression("businessunit");
exp.ColumnSet = new ColumnSet(true);
EntityCollection entities = ConnectionHelper.CrmService.RetrieveMultiple(exp);
Guid ParentBusinessUnitId = Guid.Empty;
Guid OrganizationId = Guid.Empty;
foreach (Entity ent in entities.Entities)
ParentBusinessUnitId = new Guid(ent[“businessunitid”].ToString());
EntityReference org = (EntityReference)ent[“organizationid”];
OrganizationId = org.Id;
When you have this value (of a Parent Business Unit) you can then start creating your own units relating that parent to them. For consistency, you will also want to get the OrganizationId to ensure consistency within your deployment when creating these units on your own.
Entity busUnit = new Entity("businessunit");
busUnit["name"] = "My New Business Unit";
busUnit["parentbusinessunitid"] = new EntityReference("businessunit", ParentBusinessUnitId);
busUnit["organizationid"] = new EntityReference("organization", OrganizationId);
Keep in mind, for this exercise, I had a very flat structure, if you had a very hierarchical structure you would need to ensure you find the correct parent unit each time.
Once executed, you’ll have a new business unit. If you were to execute this code a second time, you would receive an error as the business unit already exists and in order to clear it out you will need to disable it and then delete it.