首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CRM 2011: Plug-in - fetch语句,从子实体继承总计

CRM 2011: Plug-in - fetch语句,从子实体继承总计
EN

Stack Overflow用户
提问于 2013-01-24 19:04:24
回答 2查看 3.3K关注 0票数 1

我希望建立一个相当简单的插件,计算使用和剩余的“单位”的数量。我有两个自定义实体(父) bc_learninglicences &(子) bc_llbalance,插件在创建bc_llbalance时触发,另一个在更新时触发。

bc_llbalance:包含

bc_learninglicense (父实体bc_learninglicences /bc_name上的查找字段)

bc_units (此记录使用的单位)

bc_learninglicences:包含

bc_name

bc_unitsquantity (设置为单位总数)

bc_unitsused (需要继承bc_llbalance上bc_units的和)

bc_unitsremaining (简称bc_unitsquantity - bc_unitsused )

好了,我已经包含了我一直在尝试弄清楚如何让bc_unitsused继承总和的代码……

附注:我刚开始为CRM 2011开发,只有几周/几个项目的经验。

代码语言:javascript
复制
// Obtain the execution context from the service provider.
Microsoft.Xrm.Sdk.IPluginExecutionContext context (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService =(ITracingService)serviceProvider.GetService(typeof(ITracingService));

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
    // Obtain the target entity from the input parmameters.
    Entity entity = (Entity)context.InputParameters["Target"];

    IOrganizationServiceFactory serviceFactory =(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

    EntityReference a = (EntityReference)entity.Attributes["bc_learninglicense"];// ((EntityReference)targetEntity.Attributes["bc_learninglicense"]).Id;

    if (entity.LogicalName == "bc_llbalance")
    {  
        //fetchxml to get the sum total of estimatedvalue
        string value_sum = string.Format(@"<fetch distinct='false' mapping='logical'
          aggregate='true'><entity name='bc_llbalance'><attribute name='bc_units'
          alias='units_sum' aggregate='sum' /><filter type='and'><condition
          attribute='bc_learninglicense' operator='eq' value='{0}' uiname=''</filter></entity>
          </fetch>", a.Id);

        FetchExpression fetch = new FetchExpression(value_sum);
        EntityCollection value_sum_result = service.RetrieveMultiple(fetch);
        decimal TotalValue = 0;
        // decimal TotalValue = 0;

        foreach (var c in value_sum_result.Entities)
        {
            TotalValue = ((Decimal)((AliasedValue)c["value_sum"]).Value);
        }
        Entity llc = new Entity("bc_learninglicences");
        llc.Id = a.Id;
        llc.Attributes["bc_unitsused"] = TotalValue;
        service.Update(llc);
    }
}

所以我认为问题出在与父母的联系上

实体"bc_learninglicences","bc_learninglicense“是子项上的查找字段

实体"bc_llbalance“。

希望这是有意义的:基本上它不工作

我从crm收到此错误

代码语言:javascript
复制
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Unexpected exception from plug-in (Execute): LearningLicenses.LearningLicenses: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.Detail: 
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
  <ErrorCode>-2147220956</ErrorCode>
  <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
  <Message>Unexpected exception from plug-in (Execute): LearningLicenses.LearningLicenses: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.</Message>
  <Timestamp>2013-01-24T13:11:51.2373399Z</Timestamp>
  <InnerFault i:nil="true" />
  <TraceText>

[LearningLicenses: LearningLicenses.LearningLicenses]
[c1b35170-c563-e211-8c6d-b499bafd5e5b: LearningLicenses.LearningLicenses: Create of bc_llbalance]


</TraceText>
</OrganizationServiceFault>

对此解决方案的任何建议或帮助都将不胜感激。

感谢你花时间来帮助我做这件事!

我还有一些jscritp on load of parent form,它从子实体的子网格中计算总和:这只是为了澄清我需要实现什么……这是不够的,因为父窗体只在加载时更新,而带有插件的bc_learninglicences将在创建bc_llbalance时更新。

代码语言:javascript
复制
      function timeout(){
     setTimeout(calcUnitTotal, 3000);
    }

  function calcUnitTotal(){

   var grid = document.getElementById('Lines').control; 
   var ids = gridControl.get_allRecordIds();

   var sum = 0;
   var cellValue;

  for(i = 0; i < ids.length; i++) {

     var cellValue = grid.get_selectedRecords('bc_units')[i].value;
     var number = Number(cellValue.replace(/[^0-9\.]+/g,""));
     sum = sum + number;
                                                    }


   Xrm.Page.data.entity.attributes.get('bc_unitsused').setValue(sum);

    var val1 = Xrm.Page.getAttribute('bc_unitsquantity').getValue(); 

    if(val1 != null && sum != null )
       {

    var result = val1 -  sum;

    Xrm.Page.data.entity.attributes.get('bc_unitsremaining').setValue(result); 

     }
      else { alert(val1 + sum + "error: Values not passed for Remaining") }

     }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-25 20:14:12

让它工作在这里是希望它能帮助别人的代码:

代码语言:javascript
复制
public void Execute(IServiceProvider serviceProvider)
    {
        {


            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            if (context.InputParameters.Contains("Target") &&
                    context.InputParameters["Target"] is Entity)
            {
            Entity entity = (Entity)context.InputParameters["Target"];
                Guid a = ((EntityReference)entity["bc_learninglicense"]).Id;
                Entity llc = new Entity("bc_learninglicences");
                llc.Id = a;

                        //fetchxml to get the sum total of estimatedvalue
            string value_sum = string.Format(@"         
                <fetch distinct='false' mapping='logical' aggregate='true'> 
                    <entity name='bc_llbalance'>
                        <attribute name='bc_units' alias='units_sum' aggregate='sum' />
                           <filter type='and'>
                            <condition attribute='bc_learninglicense' operator='eq' value='{0}' uiname='' uitype='' />
                           </filter>
                    </entity>
                </fetch>", a);

                       EntityCollection value_sum_result = service.RetrieveMultiple(new FetchExpression(value_sum));
                       decimal TotalValue = 0;
                       foreach (var c in value_sum_result.Entities)
                       {
                            TotalValue += ((Decimal)((AliasedValue)c["units_sum"]).Value);
                       }       
                        llc.Attributes["bc_unitsused"] = TotalValue;
                        service.Update(llc);
            }
        }
     }  
票数 2
EN

Stack Overflow用户

发布于 2013-01-24 21:38:31

错误

代码语言:javascript
复制
The given key was not present in the dictionary

表示您正在尝试检索属性包中不存在的属性。

我猜这一行是导致异常的原因:

代码语言:javascript
复制
TotalValue = ((Decimal)((AliasedValue)c["value_sum"]).Value);

这里假设值value_sum存在,但也可能不存在。

测试这一点的一种简单方法是编写如下代码:

代码语言:javascript
复制
if (c.Attributes.ContainsKey("value_sum"))
{
    throw new InvalidPluginException("Test - yep no key in the dictionary here!");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14499797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档