Search code examples
c#pluginsdynamics-crmcrmxrm

CRM Plug-in C#, How to set lookup field according to another lookup field in post-event?


I have a custom entity student, each student has a department, and each department belongs to a campus (department and campus are lookup fields).

What I am trying to do is to create a new account and choose a department for him.

Then the plugin changes the campus according to the selected department.

This is my code, could someone explain to me which steps I need to do.

        var context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext;

        Entity student = context.InputParameters["Target"] as Entity;
        string Department = string.Empty;

        if (student.Contains("karam_department"))
        {
            Department = student.GetAttributeValue<>("karam_department");
        }

Solution

  • I would recommend you to do this in pre-event of create/update, hence you can set the campus attribute in target itself, this will avoid another service.Update. You have to just query the corresponding campus from the selected department, then set in target Entity.

    var context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext;
    
    Entity student = context.InputParameters["Target"] as Entity;
    
    //get the department from target
    EntityReference department = student.GetAttributeValue<EntityReference>("karam_department");
    
    if (department != null)
    {
    //retrieve the campus from department
    Entity deptEntity = service.Retrieve("karam_department", Department.Id, new ColumnSet("karam_campus"));
    
    //set the campus attribute in target itself
    student["karam_campus"] = deptEntity.GetAttributeValue<EntityReference>("karam_campus");
    
    }