sr28
sr28

Reputation: 5106

How can you change the Business Unit of a user in CRM programmatically?

I've done the following, which throws no errors but doesn't update my users Business Unit:

QueryExpression query = new QueryExpression();
query.EntityName = "systemuser";
query.ColumnSet = new AllColumns();

ConditionExpression ce = new ConditionExpression();
ce.AttributeName = "businessunitid";
ce.Operator = ConditionOperator.Equal;
ce.Values = new string[] { My BU Guid };

ConditionExpression ce2 = new ConditionExpression();
ce2.AttributeName = "lastname";
ce2.Operator = ConditionOperator.Equal;
ce2.Values = new string[] { Users Lastname };

FilterExpression filter = new FilterExpression();
filter.Conditions = new ConditionExpression[] { ce, ce2 };
query.Criteria = filter;

try
{
    BusinessEntityCollection UserCollection = crmService.RetrieveMultiple(query);
    foreach (BusinessEntity be in UserCollection.BusinessEntities)
    {
        //Update users BU. Roles will need to be added back in.
        Guid newBu = new Guid(New BU Guid);
        systemuser su = (systemuser)be;
        su.businessunitid.Value = newBu;
        TargetUpdateSystemUser sysuserUpdate = new TargetUpdateSystemUser() { SystemUser = su };
        UpdateRequest userBUUpdate = new UpdateRequest() { Target = sysuserUpdate };
        crmService.Execute(userBUUpdate);
    }
catch
{
}

At the moment this returns 1 user and throws no errors. However, on checking the user in CRM their BU hasn't changed. I've also tried simply crmService.Update(su) but that doesn't work either. What else do I need to do?

Upvotes: 0

Views: 2242

Answers (1)

Guido Preite
Guido Preite

Reputation: 15128

you can't update the business unit as other standard fields.

You need to use a SetBusinessSystemUserRequest

https://msdn.microsoft.com/en-us/library/bb929627.aspx

Upvotes: 3

Related Questions