【问题标题】:How to null check on Money Field in C#?如何在 C# 中对 Money 字段进行空检查?
【发布时间】:2018-01-18 09:02:10
【问题描述】:

我想在 .net MVC Web 服务中对 money 字段进行空检查 如何进行空检查 我写了这个,但我没有得到答案

//create module
public Money Amount { get; set; }

//Null Check
if ((EntityObject.Amount) != null)
{
    object Entity.Attributes.Add("budget amount", EntityObject.Amount);
}

如何在 Money 字段写空检查?

【问题讨论】:

  • 它应该可以工作。如果您已初始化金额字段,Amount.Value 会为您提供一个十进制值,默认为 0。
  • 当我写 Amount.Value 它给出错误

标签: c# asp.net-mvc dynamics-crm


【解决方案1】:

Money 是一种特殊的数据类型,您必须使用GetAttributeValue 进行如下处理。

Money myMoneyField = (Money)EntityObject.GetAttributeValue<Money>(Amount);

decimal actualAmount;

if (myMoneyField != null)
{
    actualAmount = myMoneyField.Value;
}
else 
{ 
    actualAmount = 0; 
}

Entity.Attributes.Add("budget_amount", new Money(actualAmount));

【讨论】:

  • 阿伦一如既往地给出了惊人的答案。我将它与对 preEntityImage 的类似检查结合使用,以确保我的代码不会因 Null 货币值而呕吐。很棒的信息,再次感谢 Arun!
【解决方案2】:

Entity.GetAttributeValue&lt;T&gt; Method (String) 可以避免空值,但请注意它会为某些数据类型返回 Default values

http://www.crmanswers.net/2015/04/getattributevalue-demystified.html https://msdn.microsoft.com/en-us/library/gg326129.aspx

如果您使用的是后期绑定Entity 类,那么您可以执行以下操作:

if ((EntityObject.Attributes.Contains("youMoneyFieldName")
{
   decimal moneyInDecimal = ((Money)EntityObject["youMoneyFieldName"]).Value;
   object Entity.Attributes.Add("budget amount", new Money(moneyInDecimal));
}

在检查空值之前,请确保您已在查询中检索到该属性,如下所示:

// 检索包含其多个属性的帐户。

ColumnSet cols = new ColumnSet(
    new String[] { "youMoneyFieldName" });

EntityObject retrievedEntity = (EntityObject)_serviceProxy.Retrieve("yourEntityName", GuidId, cols);

https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.iorganizationservice.retrieve.aspx

【讨论】:

    猜你喜欢
    • 2016-02-22
    • 2017-11-02
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2019-10-18
    相关资源
    最近更新 更多