通常情況下在插件中取Entity中的欄位值是通過強轉或者GetAttributeValue方式,但在實際插件代碼中,去判斷Moeny類型時,做一些直接的計算想一行代碼設置值,最好還是先判斷一下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;