CRM 2011 - set or assign record owner

Hi,

Just a recap of how to set the record owner or assign a new owner through the sdk.

When creating a record, you don't need to use AssignRequest. Simply set the OwnerId and call SaveChanges of your context.


1
2
3
4
5
6
7
8
var contact = new Contact()
{
    FirstName = "Andreas",
    LastName = "Wijaya",
    OwnerId = new EntityReference(Team.EntityLogicalName, <teamguid>) //can be User as well
};
myService.AddObject(contact);
myService.SaveChanges();

But if the record already exists, then you must use AssignRequest to assign the record to the new owner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Assign ownership by teamname
public static void AssignOwnerToTeam(IOrganizationService service, Entity entity, string teamName)
{
    using (MyServiceContext myService = new MyServiceContext(service))
    {
        var team = myService.TeamSet.Where(t => t.Name.Contains(teamName)).FirstOrDefault();
 
        AssignRequest assignOwner = new AssignRequest
        {
            Assignee = new EntityReference(team.LogicalName, team.Id),
            Target = new EntityReference(entity.LogicalName, entity.Id)
        };
 
        service.Execute(assignOwner);
    }
}

HTH,
Andreas

Comments

  1. Thank you for the explanation! I looked for this information hours and I tried to do a lot of things but nothing worked. On your blog I can always find what I need. Thank you so much !

    ReplyDelete

Post a Comment

Popular posts from this blog

SharePoint 2013 anonymous access add attachments to list item

CRM Plugin - Parent and Child Pipeline