天天看點

Dynamic CRM插件中擷取Entity屬性值問題

通常情況下在插件中取Entity中的字段值是通過強轉或者GetAttributeValue方式,但在實際插件代碼中,去判斷Moeny類型時,做一些直接的計算想一行代碼設定值,最好還是先判斷一下entity中有沒有這個字段,Entity實體通過查詢傳回或者插件的目前操作實體都是隻傳回有值的字段,沒有值的字段不會再Entity中

插件中擷取Entity不同類型字段時稍有差別,一般用如下兩種方式:

Entity targetEntity = (Entity)context.InputParameters["Target"];
1.decamil val = Convert.ToDecimal(targetEntity["new_cmremainingamount"]);
2.decamil val =  targetEntity.GetAttributeValue<decimal>("new_cmremainingamount");      

即通過強轉或者GetAttributeValue方式,第一種方式不建議使用,指派時用這種方式會比較簡潔一些,但在擷取值時,直接拿,如果值為空則會抛出空指針異常,用第二種方式,如果值為空則傳回null,不為空就正常傳回值。

附上CRM中字段類型:

貨币:new Money(Decimal)
查找:new EntityReference(objecttypename,Guid)
下拉:new OptionSet(Int)
選項集:false/true
時間:DateTime
整數:Integer
十進制數:Decimal
浮點數:Double
單行/多行文本:String      

但在實際插件代碼中,去判斷Moeny類型時,做一些直接的計算想一行代碼設定值,就最好還是先判斷一下entity中有沒有這個字段,Entity實體通過查詢傳回或者插件的目前操作實體都是隻傳回有值的字段,沒有值的字段不會再Entity中,是以使用以下方式:

if (!targetEntity.Contains("new_cmremainingamount")&& !targetEntity.Contains("new_partsremainingamount"))
{
   return;
}      

當然上面這種很常見,結合到一行代碼中如下:

decimal singleVolume = 0;
decimal singleWeight = 0;
singleVolume = !detailEntity.Contains("new_singlevolume") ? 0 : detailEntity.GetAttributeValue<decimal>("new_singlevolume");
singleWeight = !detailEntity.Contains("new_singleweight") ? 0 : detailEntity.GetAttributeValue<decimal>("new_singleweight");
decimal amountBalance = 0;
foreach (Entity en in entityCollection.Entities) 
{
  amountBalance += !en.Contains("new_cmremainingamount") ? 0 : en.GetAttributeValue<Money>("new_cmremainingamount").Value;
}
或者也可以通過?.的方式
 amountBalance += en.GetAttributeValue<Money>("new_cmremainingamount")?.Value  ?? 0;