如何在创建实体记录时插入自定义字段的值?

问题描述 投票:1回答:1

我面临有关如何通过创建新的systemuser插入自定义字段值的问题。

在Microsoft CRM系统中,有systemuser表,并且我有一个名为“ SSOID”的自定义字段,而“ SSOID”的值是我从webapi获得的。

我的要求是,当我进入CRM的systemuser创建页面时,我将域名值输入到域名文本框中,其他字段(例如firstname,lastname和businessID)将基于域名自动填充。它们来自活动目录。

同时,我还调用webapi以获得基于域名的SSOID。

我想要的是单击保存按钮之后,应该创建新的系统用户,并且还应该将SSOID与新的系统用户一起插入。

但是现在当我单击按钮时,发生了一些错误

不存在ID为5ab7eb74-511a-ea11-810b-005056ba5450的用户设置

下面是我的代码,它看起来很简单,但是发生了一些错误;

IPluginExecutionContext context;
IOrganizationServiceFactory factory;
IOrganizationService service;
// 获取执行上下文
context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// 获取服务工厂
factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
// 获取服务
service = factory.CreateOrganizationService(context.UserId);

if (context.MessageName.ToLower() == "create"
&& context.InputParameters.Contains("Target")
&& context.InputParameters["Target"] is Entity)
{
    try
    {

        var domainName = "";
        Entity entity = (Entity)context.InputParameters["Target"];
        if (context.Depth > 1)
        { return; }
        if (entity.Attributes.Contains("domainname"))
        {
            domainName = entity["domainname"].ToString();
        }

        var SSOId = " get from webapi";

        if (!string.IsNullOrEmpty(SSOId))
        {
            var businessEntityRef = (Microsoft.Xrm.Sdk.EntityReference)(entity.Attributes["businessunitid"]);
            var businessunit = service.Retrieve(businessEntityRef.LogicalName, businessEntityRef.Id, new ColumnSet(true));
            entity["businessunitid"] = businessEntityRef; // businessunit id is look up field comes from businessunit reference table
            entity["domainname"] = entity["domainname"];
            entity["lastname"] = entity["lastname"];
            entity["firstname"] = entity["firstname"];
            entity["new_ssoid"] = SSOId;
            service.Update(entity);  //i can't use create method, it shows "The specified Active Directory user already exists as a Dynamics 365 user"
        }
        else
        {
            throw new InvalidPluginExecutionException("userID not exist");
        }
    }
    catch (Exception ex)
    {
        throw new InvalidPluginExecutionException(ex.Message);
    }
}

我是CRM插件开发的新手,谁能指导我如何解决此问题?

c# plugins dynamics-crm crm
1个回答
0
投票

请使用下面的代码:

var SSOId = " get from webapi";

if (!string.IsNullOrEmpty(SSOId))
{
    Entity entityToUpdate = new Entity("systemuser", new Guid(entity.Id));
    entityToUpdate["new_ssoid"] = SSOId;
    service.Update(entityToUpdate);
}
else
{
    throw new InvalidPluginExecutionException("userID not exist");
}

您需要创建一个新的实体对象实例,以在创建记录后进行更新(创建后的异步插件)。

此外,如果在没有错误的情况下引发异常,则事务将回滚。考虑一下。

© www.soinside.com 2019 - 2024. All rights reserved.