无法转换CRM 2013插件类型的对象

时间:2015-02-18 11:52:03

标签: dynamics-crm dynamics-crm-2013

我有一个Synchronous插件,可以在任何机会创建/删除/更新时运行。在插件中,如果出现任何错误,我已经创建了一个将日志插入数据库的函数。

在第一个字段中,如果是EntityId,那么我正在编写以下代码:

foreach (PropertyBagEntry entry in (IEnumerable<PropertyBagEntry>)context.InputParameters.Values)
{

        DynamicEntity entity = (DynamicEntity)entry.Value;
        foreach (Property property in (IEnumerable<Property>)entity.Properties)
        {
            if (property.GetType().Name == "KeyProperty")
            {
                str4 = ((Key)entity.Properties[property.Name]).Value.ToString();
                break;
            }
        }
}

在str4中我得到当前进程的EntityId。

但它经常提供一个例外:

未处理的异常:System.InvalidCastException:无法转换类型的对象 &#39; ValueCollection [System.String,System.Object的]&#39; 输入&#39; System.Collections.Generic.IEnumerable`1 [Microsoft.Crm.Sdk.PropertyBagEntry]&#39;

我已经确定以下行给出了错误

foreach((IEnumerable)context.InputParameters.Values中的PropertyBagEntry条目)

任何人都有想过以另一种方式转换此行吗?

3 个答案:

答案 0 :(得分:0)

我的理解是你想获得当前记录的GUID,如果是这种情况,那么你可以这样做:

public void Execute(IServiceProvider serviceProvider)
{
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

    try
    {
        if (context.MessageName == "Create" || context.MessageName == "Update")
        {
            if (context.InputParameters.Contains("Target") && (context.InputParameters["Target"] is Entity))
            {
                Entity currentEntity = (Entity) context.InputParameters["Target"];
                Guid currentRecordGuid = currentEntity.Id;
            }

        }
    }
    catch (Exception ex)
    {

    }
}

答案 1 :(得分:0)

我认为该集合的类型因消息而异。如果您希望在插件中获取记录的ID,则此辅助函数可能会派上用场:

public static Guid GetEntityIdFromContext(IPluginExecutionContext context)
{
    string messageName = context.MessageName;
    if (context.PrimaryEntityId != Guid.Empty)
    {
        return context.PrimaryEntityId;
    }
    else if (messageName == "Create")
    {
        return new Guid(context.OutputParameters["id"].ToString());
    }
    else
    {
        return context.PrimaryEntityId;
    }
}

如果这没有帮助,您介意提供导致错误的消息吗?

答案 2 :(得分:0)

如果

  

未处理的异常:System.InvalidCastException:无法强制转换   要键入的'ValueCollection [System.String,System.Object]'类型的对象   'System.Collections.Generic.IEnumerable`1 [Microsoft.Crm.Sdk.PropertyBagEntry]'

确实是您的错误,而不是您的问题不在行

foreach (Property property in (IEnumerable<Property>)entity.Properties)

但是用行:

foreach (PropertyBagEntry entry in (IEnumerable<PropertyBagEntry>)context.InputParameters.Values)

context.InputParameters.Values的类型不能转换为IEnumerable